【问题标题】:plot.bar(), duplicate values are removed in the x-axis?plot.bar(),x轴上的重复值被删除了吗?
【发布时间】: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 个值.不知道是什么原因。

我的问题是:

  1. 可以像我一样提取 x 和 y 值,还是应该将某些形式的值转换为字符串或列表?
  2. 如何避免在 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.plotpandas.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


【解决方案1】:

试试:

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)

【讨论】:

  • OP 说他们希望避免使用 pandas 进行绘图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
  • 2016-12-06
  • 2016-05-07
  • 1970-01-01
  • 2016-04-17
  • 2020-10-14
相关资源
最近更新 更多