【问题标题】:How to create an unequally spaced bar chart?如何创建不等间距的条形图?
【发布时间】:2018-01-09 17:49:45
【问题描述】:

使用plot.barh 创建一个具有等间距列的条形图。 但是,我有一列具有不等间距的值 (df1['dist']),我想在图中使用它来提供更多信息:

df1 = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b'])
df1['dist'] = pd.Series([1,5,6.5,15,45], index=df1.index)

df1.plot.barh(['dist'],['a','b'],stacked=True, width=.6, color = ['y','b'])
plt.show()

这可能吗?

【问题讨论】:

  • 这是使用什么库 - pandas?
  • @jcfollower 是的,是熊猫。

标签: python pandas matplotlib charts


【解决方案1】:

您可以使用来自matplotlibbarh 函数“手动”创建条形图:

import pandas as pd
from matplotlib import pyplot as plt
import numpy as np

df1 = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b'])
df1['dist'] = pd.Series([1,5,6.5,15,45], index=df1.index)

fig,ax = plt.subplots()

ax.barh(df1['dist'],df1['a'],height =1)
ax.barh(df1['dist'],df1['b'],left=df1['a'], height =1)
plt.show()

结果如下:

我不确定这是否真的看起来更好,因为现在条形很薄。但是,您可以使用height 参数对其进行调整。

【讨论】:

  • 谢谢,它适用于一组 2 个系列。但是,如果我增加更多系列,我会得到一些奇怪的结果 - 可能我误解了这个概念?这是一个例子:df1 = pd.DataFrame(np.random.rand(5, 4), columns=['a', 'b' ,'c', 'd']) df1['dist'] = pd.Series([1,5,6.5,15,45], index=df1.index) ax.barh(df1['dist'],df1['a'],height =1, color = 'r') ax.barh(df1['dist'],df1['b'],left=df1['a'], height =1, color = 'g') ax.barh(df1['dist'],df1['c'],left=df1['b'], height =1, color = 'b') ax.barh(df1['dist'],df1['d'],left=df1['c'], height =1, color = 'k')
  • 为我的上一条评论找到了解决方案here:
  • @mati 你面临的问题是left 关键字,它告诉barh 从哪里开始酒吧。对于第二列,left 只是第一列的值,但对于第三列,您必须使用第一列和第二列的值之和。如果您有超过三列,当然最好循环执行此操作,并将 left 值的运行总和存储在专用列表中,就像您链接的问题的答案之一一样。
猜你喜欢
  • 2015-06-09
  • 1970-01-01
  • 2020-12-02
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
相关资源
最近更新 更多