python - 如何为我的数据创建条形图?

标签 python pandas matplotlib

我想使用 pandas 和 matplotlib 创建一个简单的两侧条形图(每个 X 轴有两个条形图,如 here )。

df = 
ID      Rank1   Rank2
243390  120.5   9.0
243810  37.5    10.0
253380  77.0    5.0
255330  29.0    8.0
256520  177.5   25.0

我能够创建一个包含两个条形的条形图,但该图没有出现。

fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
bar_width = 0.35
opacity = 0.8

rects1 = plt.bar(df["ID"], df["Rank1"], bar_width, 
                 alpha=opacity,
                 color='b',
                 label='Rank1')

rects2 = plt.bar(df["ID"] + bar_width, df["Rank2"], bar_width, 
                 alpha=opacity,
                 color='r',
                 label='Rank2')
plt.legend()
#plt.tight_layout()
plt.show() 

最佳答案

您的 bar_widths 对于您的 x 轴比例来说太小了。试试这个:

fig = plt.figure(figsize=(12,8))
ax = fig.add_subplot(111)
bar_width = 200
opacity = 0.8

rects1 = plt.bar(df["ID"]- bar_width/2, df["Rank1"], bar_width, 
                 alpha=opacity,
                 color='b',
                 label='Rank1')

rects2 = plt.bar(df["ID"] + bar_width/2, df["Rank2"], bar_width, 
                 alpha=opacity,
                 color='r',
                 label='Rank2')
plt.legend()
#plt.tight_layout()
plt.show() 

enter image description here

关于python - 如何为我的数据创建条形图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47892339/

相关文章:

python:分散不显示

python - 使用 asyncio 的非阻塞 I/O

python - TkKinter 是否广泛用于构建用户界面?

python - 如何使用带有 Pandas 数据帧的请求来创建多个 Get http 请求?

python - 一旦达到特定值,就删除高于特定值的行

python - 如何理解 ndarray.reshape 函数?

python - 如何在 Python 中{pivot|denormalize|manipulate} CSV 表

python - 读取 CSV 并绘制彩色折线图

python - Matplotlib - 以 A4 格式拟合所有子图

python - 表格单元格的 2 级或 3 级着色的条件格式