2017-08-02 82 views
0

使用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() 

这可能吗?

+1

这是什么库使用 - 熊猫? – jcfollower

+0

@jcfollower是的,它是熊猫。 – mati

回答

2

您可以创建 '手工' 条形图使用barh功能从matplotlib

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() 

下面是结果:

enter image description here

我不知道如果这实际上看起来更好,因为现在酒吧非常薄。但是,您可以使用参数height来调整它们。

+0

谢谢,它适用于一系列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')' – mati

+0

为我最近的评论找到了一个解决方案[here:](https://stackoverflow.com/a/16654564/4053508) – mati

+0

@mati你面对的问题用'left'关键字,它告诉'barh'在哪里开始吧。对于第二列,“left”只是第一列的值,但对于第三列,则必须使用第一列和第二列的值的总和。如果你有三个以上的列,当然最好是在一个循环中完成这个操作,并将“左”值的运行总和存储在一个专用列表中,就像在你链接的问题的答案之一中一样。 –