【发布时间】:2021-12-11 04:42:09
【问题描述】:
我以以下 DataFrame df 为例,我想将价格绘制为 x 轴,将 share_1 和 share_2 绘制为条形堆叠形式的 y 轴。我想避免使用 pandas.plot 而是使用 plt.bar 并从 Dataframe 中提取 x_values 和 y_values。
Price size share_1 share_2
10 1 0.05 0.95
10 2 0.07 0.93
10 3 0.1 0.95
20 4 0.15 0.75
20 5 0.2. 0.8
20 6 0.35 0.65
30 7 0.5. 0.5
30 8 0.53 0.47
30 9 0.6. 0.4
这是我继续的方式:
x= df['Price']
y1= df['share_1']
y2= df['share_2']
plt.bar(x,y1,label='share_1')
plt.bar(x,y2,label='share_2')
我仍然有问题,matplotlib 删除了 x 轴上的重复值,或者重复值的平均值是自动计算的,所以我在 x 轴上得到 3 个值,而不是我想要的 6 个值.不知道是什么原因。
我的问题是:
- 可以像我一样提取 x 和 y 值,还是应该将某些形式的值转换为字符串或列表?
- 如何避免在 x 轴中删除重复值的事实。我想拥有与 DataFrame 中完全相同数量的 x_values
【问题讨论】:
-
你为什么不想要 pandas.plot?无论如何,它在后台使用 matplotlib。
-
因为我更喜欢使用 fig, ax= plt.subplots() 而不是 pandas.plot
-
您也可以将
ax传递给pandas plot:fig,ax = plt.subplots(); df.plot.bar(ax=ax)。 -
@jess - 我用
plt.plot和pandas.plot提供了一个答案,指定了要绘制的轴。我强烈建议使用后者(即pandas)。 -
@QuangHoang 我使用 fig 尝试了你的代码, ax = plt.subplots() 不幸的是它没有工作,df.plot.bar(x="Price", y=["share_1"," share_2"],stacked=True,ax=ax) 也不起作用!我想知道问题是否出在木星上,因为我可以找到原因
标签: python pandas matplotlib duplicates x-axis