python - 在同一轴上绘制多个条形图

标签 python pandas matplotlib

我想使用同一斧头在一行上绘制多个条形图,但似乎 pandas 绘图函数每次都会删除我之前的绘图。

例如:

import pandas as pd
import pylab as plt

fig, ax = plt.subplots()
df = pd.DataFrame({'lab':['D', 'E', 'F'], 'val':[10, 30, 20]})
df.plot.bar(x='lab', y='val', rot=0, ax=ax)
df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
df.plot.bar(x='lab', y='val', rot=0, ax=ax)
ax.set_xlim(-.5, 6)
plt.show()

给我

barplot fail

我尝试使用 pandas 函数的 xticks 参数,但它不起作用。

最佳答案

您需要设置条形在 X 轴上的位置

https://matplotlib.org/gallery/lines_bars_and_markers/barchart.html#sphx-glr-gallery-lines-bars-and-markers-barchart-py

men_means, men_std = (20, 35, 30, 35, 27), (2, 3, 4, 1, 2)
women_means, women_std = (25, 32, 34, 20, 25), (3, 5, 2, 3, 3)

ind = np.arange(len(men_means))  # the x locations for the groups
width = 0.35  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind - width/2, men_means, width, yerr=men_std,
                color='SkyBlue', label='Men')
rects2 = ax.bar(ind + width/2, women_means, width, yerr=women_std,
                color='IndianRed', label='Women')

请注意“ind”部分 - 用于确定条形的位置。另请注意,条形的颜色已拼写出来。

关于python - 在同一轴上绘制多个条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54811266/

相关文章:

python - 为什么 dataframe.shape[0] 打印一个整数,而 dataframe.columnname.shape 打印一个元组

python - Pandas 根据另一列的值映射列数据,使用 if 来确定要使用的字典

python - 将 Pandas Dataframe 的选择保存到 csv

python - NetworkX 反向循环节点

python - 从 Pandas DataFrame 中删除一列

python - Matplotlib imshow() 的手动定义轴标签

python - 在 Python 的 matplotlib 中使用时间序列的百分位数设置颜色渐变

python - 获取条形图的颜色matplotlib

python - 具有表面渐变的颜色 matplotlib plot_surface 命令

java - Python、C/++、java...有没有用于比较音频信号的 api?