用matplotlib绘制的条形图,条形重合
import pandas as pdimport matplotlib.pyplot as plt
phones = pd.read_excel('D:\测试.xlsx',)
plt.rcParams ['font.sans-serif'] = ['SimHei']
plt.rcParams ['axes.unicode_minus'] = False
x = phones['品牌']
y = phones['淘宝销量']
z = phones['京东销量']
plt.bar(x,y,color='g',label="淘宝销量",alpha=0.5,width=0.4)
plt.bar(x,z,color='b',label='京东销量',width=0.4)
plt.legend()
plt.show()
excel表就是以下这些内容
品牌 淘宝销量 京东销量
小米 9 8
荣耀 20 30
华为 5 4
代码运行后出现的图表两条柱状是重合的,
直接在x后加数字会报错TypeError: can only concatenate str (not "float") to str
请问应该用什么方法才能将两个条形分开,
求解答
直接抄官网import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
labels = ['小米', '荣耀', '华为']
taobao =
jingdong =
x =
width = 0.35# the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(, taobao, width, label='淘宝')
rects2 = ax.bar(, jingdong, width, label='京东')
# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel('销量')
ax.set_title('销量对比')
ax.set_xticks(x)
ax.set_xticklabels(labels)
ax.legend()
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3),# 3 points vertical offset
textcoords="offset points",
ha='center', va='bottom')
autolabel(rects1)
autolabel(rects2)
fig.tight_layout()
plt.show()
suchocolate 发表于 2021-12-10 16:07
直接抄官网
感谢回答
页:
[1]