Python 如何从dataframe创建具有辅助功能的条形图

Python 如何从dataframe创建具有辅助功能的条形图,python,matplotlib,pandas,Python,Matplotlib,Pandas,我想创建一个包含在Pandas数据框中的两个系列(比如“a”和“B”)的条形图。如果我想使用不同的y轴来绘制它们,我可以使用次级y轴: df = pd.DataFrame(np.random.uniform(size=10).reshape(5,2),columns=['A','B']) df['A'] = df['A'] * 100 df.plot(secondary_y=['A']) 但如果我想创建条形图,则忽略等效命令(它不会在y轴上放置不同的比例),因此“A”中的条形太大,无法区分“B

我想创建一个包含在Pandas数据框中的两个系列(比如“a”和“B”)的条形图。如果我想使用不同的y轴来绘制它们,我可以使用次级y轴:

df = pd.DataFrame(np.random.uniform(size=10).reshape(5,2),columns=['A','B'])
df['A'] = df['A'] * 100
df.plot(secondary_y=['A'])
但如果我想创建条形图,则忽略等效命令(它不会在y轴上放置不同的比例),因此“A”中的条形太大,无法区分“B”中的条形:

df.plot(kind='bar',secondary_y=['A'])
我如何直接在熊猫身上做到这一点?或者,您将如何创建这样的图表


我使用的是pandas 0.10.1和matplotlib版本1.2.1。

不要认为pandas绘图支持这一点。做了一些手工matplotlib代码。。你可以进一步调整它

import pylab as pl
fig = pl.figure()
ax1 = pl.subplot(111,ylabel='A')
#ax2 = gcf().add_axes(ax1.get_position(), sharex=ax1, frameon=False, ylabel='axes2')
ax2 =ax1.twinx()
ax2.set_ylabel('B')
ax1.bar(df.index,df.A.values, width =0.4, color ='g', align = 'center')
ax2.bar(df.index,df.B.values, width = 0.4, color='r', align = 'edge')
ax1.legend(['A'], loc = 'upper left')
ax2.legend(['B'], loc = 'upper right')
fig.show()


我相信有办法迫使一个酒吧进一步调整它。将条移动得更远,一个稍微透明,等等。

好的,我最近遇到了同样的问题,即使这是一个老问题,我想我可以给出这个问题的答案,以防其他人对此失去理智。Joop给出了要做的事情的基础,当您的数据帧中只有(例如)两列时,这很容易,但是当您的两个轴有不同数量的列时,这会变得非常糟糕,因为您需要使用pandas plot()函数的position参数。在我的示例中,我使用seaborn,但它是可选的:

import pandas as pd
import seaborn as sns
import pylab as plt
import numpy as np

df1 = pd.DataFrame(np.array([[i*99 for i in range(11)]]).transpose(), columns = ["100"], index = [i for i in range(11)])
df2 = pd.DataFrame(np.array([[i for i in range(11)], [i*2 for i in range(11)]]).transpose(), columns = ["1", "2"], index = [i for i in range(11)])

fig, ax = plt.subplots()
ax2 = ax.twinx()

# we must define the length of each column. 
df1_len = len(df1.columns.values)
df2_len = len(df2.columns.values)
column_width = 0.8 / (df1_len + df2_len)

# we calculate the position of each column in the plot. This value is based on the position definition :
# Specify relative alignments for bar plot layout. From 0 (left/bottom-end) to 1 (right/top-end). Default is 0.5 (center)
# http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.plot.html
df1_posi = 0.5 + (df2_len/float(df1_len)) * 0.5
df2_posi = 0.5 - (df1_len/float(df2_len)) * 0.5

# In order to have nice color, I use the default color palette of seaborn
df1.plot(kind='bar', ax=ax, width=column_width*df1_len, color=sns.color_palette()[:df1_len], position=df1_posi)
df2.plot(kind='bar', ax=ax2, width=column_width*df2_len, color=sns.color_palette()[df1_len:df1_len+df2_len], position=df2_posi)

ax.legend(loc="upper left")

# Pandas add line at x = 0 for each dataframe.
ax.lines[0].set_visible(False)
ax2.lines[0].set_visible(False)

# Specific to seaborn, we have to remove the background line 
ax2.grid(b=False, axis='both')

# We need to add some space, the xlim don't manage the new positions
column_length = (ax2.get_xlim()[1] - abs(ax2.get_xlim()[0])) / float(len(df1.index))
ax2.set_xlim([ax2.get_xlim()[0] - column_length, ax2.get_xlim()[1] + column_length])

fig.patch.set_facecolor('white')
plt.show()
结果是:


我并没有测试所有的可能性,但不管您使用的每个数据帧中的列数是多少,它看起来都可以正常工作

你所说的等效命令不起作用是什么意思?您是否没有数字,或者数字不是您所期望的?请发布错误或描述什么不起作用您尝试手动实现了什么?你看过那张照片了吗?没有,一切都很顺利。你们有同样大小的酒吧吗?您使用的是哪个版本?我明白了,对不起,我完全错过了关键一行(现在回想起来很明显)。这在pandas 0.11中也不起作用,我建议将其作为github提交。