0

我以以下 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 个值。我不知道是什么原因。

我的问题是:

  1. 可以像我一样提取 x 和 y 值,还是应该将某些形式的值转换为字符串或列表?
  2. 如何避免在 x 轴中删除重复值的事实。我希望 x_value 的数量与 DataFrame 中的数量完全相同
4

1 回答 1

0

尝试:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.bar(x, y1, label="share_1")
ax.bar(x, y2, label="share_2", bottom=y1)
ax.set_xticks(x)
ax.legend()
ax.set_xticklabels(labels) 
plt.show()

在此处输入图像描述

顺便说一句,考虑使用pandas.plot如下:

fig,ax = plt.subplots()
df.plot.bar(x="Price", y=["share_1","share_2"], stacked=True, ax=ax)
于 2021-10-25T17:39:38.207 回答