我与之战斗应该是一项相当容易的任务。创建2系列线图。到目前为止,我设法这样做,但我认为这不是最快的方式。我想问一下是否有人知道如何更快/更聪明地做到这一点?
我遇到的问题是这两个系列的值在同一列中,值是'为了获得系列,我应该根据'类别'柱。到目前为止,我设法通过在绘制之前进行一些转换来实现。它似乎不是最快的解决方案。有没有人知道一种方法来制作这个没有变换的情节,我在下面的代码中做了什么?
我的代码:
import numpy.random as r
import pandas as pn
#generate values
values= r.random_sample(200)
labels = range(1,101)+range(1,101)
category = [x for x in 100*'a'+100*'b' ]
#create dataframe
df =pn.DataFrame({'labels': labels,
'values': values,
'category': category})
### I tired here to create plot but was unsuccessful so far. And needed to make below transformation.
#transformation
df =df.set_index('labels')
dfA= df[df['category']=='a']
del dfA['category']
dfA.columns=['values_a']
dfB=df[df['category']=='b']
del dfB['category']
dfB.columns=['values_b']
#joining
frames=[dfA,dfB]
dff= pn.concat(frames, axis=1)
#ploting
dff.plot()
提前感谢您的帮助!
答案 0 :(得分:2)
IIUC您可以使用concat
参数keys
作为列名:
#transformation
df = df.set_index('labels')
dff = pn.concat([df.loc[df['category']=='a', 'values'],
df.loc[df['category']=='b', 'values']],
axis=1,
keys=['values_a', 'values_b'])
print dff
values_a values_b
labels
1 0.240131 0.083861
2 0.137078 0.788497
3 0.017947 0.985262
4 0.053830 0.882618
5 0.772023 0.753158
6 0.258116 0.322541
7 0.837611 0.188269
8 0.551581 0.599734
... ... ...
... ... ...
... ... ...
93 0.413466 0.794807
94 0.791670 0.186960
95 0.033857 0.070732
96 0.805209 0.570014
97 0.691454 0.125113
98 0.564201 0.104882
99 0.656381 0.176520
100 0.007758 0.340838
[100 rows x 2 columns]
编辑:您可以省略concat
,然后按ax.legend
设置图例:
import matplotlib.pyplot as plt
plt.figure()
df.loc[df['category']=='a', 'values'].plot()
ax = df.loc[df['category']=='b', 'values'].plot()
ax.legend(['values_a','values_b'])
答案 1 :(得分:2)
您做必须转换您的数据,因为您不希望按原样绘制列。但有一种更简单的方法:
>>> df.pivot(index='labels', columns='category', values='values').head()
category a b
labels
1 0.133046 0.762676
2 0.717739 0.774000
3 0.059960 0.547297
4 0.464269 0.951537
5 0.227428 0.987621
>>> df.pivot(index='labels', columns='category', values='values').plot()
答案 2 :(得分:1)
你可以使用seaborn来实现这个散点图:
import seaborn as sns
sns.lmplot('labels', 'values', data=df, hue='category')
如果您更喜欢折线图:
import seaborn as sns
sns.pointplot('labels', 'values', data=df, hue='category')