使用 Pandas 从数据透视表绘图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26241840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Plotting from Pivot Table using Pandas
提问by user3307240
Let's say that I have the following pivot table (this is the one created in the documentation):
In [8]: tuples = list(zip(*[['bar', 'bar', 'baz', 'baz',
...: 'foo', 'foo', 'qux', 'qux'],
...: ['one', 'two', 'one', 'two',
...: 'one', 'two', 'one', 'two']]))
...:
In [9]: index = MultiIndex.from_tuples(tuples, names=['first', 'second'])
In [10]: df = DataFrame(randn(8, 2), index=index, columns=['A', 'B'])
In [11]: df2 = df[:4]
In [12]: df2
Out[12]:
A B
first second
bar one 0.721555 -0.706771
two -1.039575 0.271860
baz one -0.424972 0.567020
two 0.276232 -1.087401
How can I use this table to plot both 'bar' and 'baz' on the same plot with axes (second, A) (i.e. I want to create a plot with the points (one, 0.72), (two, -1.039), (one, -0.42), (two, 0.276), where the first two points are plotted in a different color than the latter two).
我如何使用这个表在同一个图上绘制 'bar' 和 'baz' 轴(第二,A)(即我想用点(一,0.72),(二,-1.039)创建一个图, (one, -0.42), (two, 0.276),其中前两个点以与后两个不同的颜色绘制)。
I tried using
我尝试使用
df2[[0]].plot()
but this plots the points sequentially on the x-axis so that they are ordered ((bar,one), .721), ((bar,two), -1.039), etc, rather than having the two 'one' points and the two 'two' points share a vertical axis.
但这会在 x 轴上按顺序绘制点,以便它们按顺序排列 ((bar,one), .721), ((bar,two), -1.039) 等,而不是有两个“one”点和两个“二”点共享一个垂直轴。
回答by user3307240
Ok, I figured it out. The key was unstacking the data first:
好的,我想通了。关键是先拆开数据:
import matplotlib.pyplot as plt
t=df2.unstack(level=0)
plt.plot(t[[0]], color='red')
plt.plot(t[[1]], color='blue')
plt.xticks(range(2), ['one','two'], size='small')
plt.show()

