python - 使用 matplotlib.pyplot python 绘制条形图
问题描述
我有一个这样的数据框:
A B C D E F index1
44544 44544 44544 44544 44544 44544 250
0 0 0 0 761 738 500
0 0 0 0 0 13 750
0 0 0 0 1 3 1000
0 0 0 0 10 11 1250
0 0 2 0 16219 8028 1500
0 0 12560 9649 102 222 1750
0 0 26406 23089 115 56 2000
现在我想使用 matplotlib 中的单选按钮绘制条形图。我尝试了以下代码:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import RadioButtons
df5=pd.read_excel(r'C:\YOIGO\hi.xlsx')
l1=df5.columns[0:6].tolist()
fig, ax = plt.subplots()
l, = ax.plot(np.array(df5.index1), np.array(df5.iloc[:,2]), lw=2, color='red')
plt.subplots_adjust(left=0.3)
t=tuple(l1)
print(t)
axcolor = 'lightgoldenrodyellow'
rax = plt.axes([0.05, 0.7, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, t)
d={}
for x in t:
d[x]=np.array(df5[x])
def hzfunc(label):
hzdict = d
ydata = hzdict[label]
l.set_ydata(ydata)
plt.draw()
radio.on_clicked(hzfunc)
plt.show()
但是上面的代码给了我正常的图而不是条形图。我可以知道如何将其转换为条形图吗?
解决方案
您的问题是plt.plot()
,当您想用来plt.bar()
创建条形图时,您正在使用它来绘制线图。
然而,plot()
和bar()
返回不同的对象,分别Line2D
和BarCollection
。因此,您需要更改回调函数中的逻辑:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import RadioButtons
d = """A B C D E F index1
44544 44544 44544 44544 44544 44544 250
0 0 0 0 761 738 500
0 0 0 0 0 13 750
0 0 0 0 1 3 1000
0 0 0 0 10 11 1250
0 0 2 0 16219 8028 1500
0 0 12560 9649 102 222 1750
0 0 26406 23089 115 56 2000
"""
df5=pd.read_table(StringIO(d), sep='\s+')
fig, ax = plt.subplots()
bars = ax.bar(np.array(df5.index1), height=np.array(df5['A']), color='red', width=200)
plt.subplots_adjust(left=0.3)
axcolor = 'lightgoldenrodyellow'
rax = plt.axes([0.05, 0.7, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, df5.columns[:-1])
def hzfunc(label):
ydata = df5[label]
for b,y in zip(bars,ydata):
b.set_height(y)
plt.draw()
radio.on_clicked(hzfunc)
推荐阅读
- python - 用户选项和验证
- python - 执行一个函数可以防止 tkinter 窗口出现
- mysql - 显示具有其他属性的组中的第一个和最后一个 mysql 记录
- python-3.x - 无法使用 selenium 从网站中定位元素
- php - Laravel 8 没有从包“\Conner\Tagging\Taggable;”中找到“标签”
- c - 时间复杂度会根据参数变化吗?
- reactjs - 开玩笑的期望语句不会等待承诺得到解决
- strapi - 如何在strapi中使用根路由(/)作为/admin
- google-sheets - 从 vlookup 检查 Google 表格中的文本而不破坏公式、文本换行或将列宽更改为“适合数据”?
- javafx - 结束时如何重置 JavaFX 媒体播放器?