2014-02-09 36 views
47

我想在pyplot中使用Pandas DataFrame对象制作一个简单的散点图,但希望绘制两个变量的有效方式,但需要第三列指定的符号(键)。我尝试过使用df.groupby的各种方式,但没有成功。下面是一个示例df脚本。这根据'key1'标记颜色,但是id喜欢看'key1'类别的图例。我关门了吗?谢谢。Pandas中的散点图/ Pyplot:如何按类别绘图

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three')) 
df['key1'] = (4,4,4,6,6,6,8,8,8,8) 
fig1 = plt.figure(1) 
ax1 = fig1.add_subplot(111) 
ax1.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8) 
plt.show() 

回答

64

您可以使用scatter此,但这需要您的数值为key1,并且您将不会看到图例,正如您注意到的那样。

对于像这样的离散类别,最好使用plot。例如:

import matplotlib.pyplot as plt 
import numpy as np 
import pandas as pd 
np.random.seed(1974) 

# Generate Data 
num = 20 
x, y = np.random.random((2, num)) 
labels = np.random.choice(['a', 'b', 'c'], num) 
df = pd.DataFrame(dict(x=x, y=y, label=labels)) 

groups = df.groupby('label') 

# Plot 
fig, ax = plt.subplots() 
ax.margins(0.05) # Optional, just adds 5% padding to the autoscaling 
for name, group in groups: 
    ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name) 
ax.legend() 

plt.show() 

enter image description here

如果你想的东西看起来像默认pandas风格,那么就更新rcParams与大熊猫样式表,并使用它的颜色生成。 (我还扭捏传说略):

import matplotlib.pyplot as plt 
import numpy as np 
import pandas as pd 
np.random.seed(1974) 

# Generate Data 
num = 20 
x, y = np.random.random((2, num)) 
labels = np.random.choice(['a', 'b', 'c'], num) 
df = pd.DataFrame(dict(x=x, y=y, label=labels)) 

groups = df.groupby('label') 

# Plot 
plt.rcParams.update(pd.tools.plotting.mpl_stylesheet) 
colors = pd.tools.plotting._get_standard_colors(len(groups), color_type='random') 

fig, ax = plt.subplots() 
ax.set_color_cycle(colors) 
ax.margins(0.05) 
for name, group in groups: 
    ax.plot(group.x, group.y, marker='o', linestyle='', ms=12, label=name) 
ax.legend(numpoints=1, loc='upper left') 

plt.show() 

enter image description here

+0

是的,看起来它会为我工作。非常感谢。 – user2989613

+0

为什么在上面的RGB例子中,符号在图例中显示两次?如何只显示一次? –

+1

@SteveSchulist - 使用'ax.legend(numpoints = 1)'只显示一个标记。有两个,就像'Line2D'一样,经常有一条线连接两个标记。 –

15

随着plt.scatter,我只能想到一个:使用代理艺术家:

df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three')) 
df['key1'] = (4,4,4,6,6,6,8,8,8,8) 
fig1 = plt.figure(1) 
ax1 = fig1.add_subplot(111) 
x=ax1.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8) 

ccm=x.get_cmap() 
circles=[Line2D(range(1), range(1), color='w', marker='o', markersize=10, markerfacecolor=item) for item in ccm((array([4,6,8])-4.0)/4)] 
leg = plt.legend(circles, ['4','6','8'], loc = "center left", bbox_to_anchor = (1, 0.5), numpoints = 1) 

,其结果是:

enter image description here

+0

另一个好建议。我也会试试这个。谢谢。 – user2989613

20

这就是简单的用Seabornpip install seaborn)作为oneliner

sns.pairplot(x_vars=["one"], y_vars=["two"], data=df, hue="key1", size=5) 做:

import seaborn as sns 
import pandas as pd 
import numpy as np 
np.random.seed(1974) 

df = pd.DataFrame(
    np.random.normal(10, 1, 30).reshape(10, 3), 
    index=pd.date_range('2010-01-01', freq='M', periods=10), 
    columns=('one', 'two', 'three')) 
df['key1'] = (4, 4, 4, 6, 6, 6, 8, 8, 8, 8) 

sns.pairplot(x_vars=["one"], y_vars=["two"], data=df, hue="key1", size=5) 

enter image description here

下面是引用数据框:

enter image description here

既然你有你的数据的三个变量列,你可能要绘制所有成对尺寸有:

sns.pairplot(vars=["one","two","three"], data=df, hue="key1", size=5) 

enter image description here

https://rasbt.github.io/mlxtend/user_guide/plotting/category_scatter/是另一种选择。

2

您也可以尝试Altairggpot这些重点是声明性可视化。

import numpy as np 
import pandas as pd 
np.random.seed(1974) 

# Generate Data 
num = 20 
x, y = np.random.random((2, num)) 
labels = np.random.choice(['a', 'b', 'c'], num) 
df = pd.DataFrame(dict(x=x, y=y, label=labels)) 

牵牛星代码

from altair import Chart 
c = Chart(df) 
c.mark_circle().encode(x='x', y='y', color='label') 

enter image description here

ggplot代码

from ggplot import * 
ggplot(aes(x='x', y='y', color='label'), data=df) +\ 
geom_point(size=50) +\ 
theme_bw() 

enter image description here

4

您可以使用df.plot.scatter,并传递一个AR射线到c =参数定义每个点的颜色:

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
df = pd.DataFrame(np.random.normal(10,1,30).reshape(10,3), index = pd.date_range('2010-01-01', freq = 'M', periods = 10), columns = ('one', 'two', 'three')) 
df['key1'] = (4,4,4,6,6,6,8,8,8,8) 
colors = np.where(df["key1"]==4,'r','-') 
colors[df["key1"]==6] = 'g' 
colors[df["key1"]==8] = 'b' 
print(colors) 
df.plot.scatter(x="one",y="two",c=colors) 
plt.show() 

enter image description here

0

这是相当哈克,但你可以使用one1Float64Index一气呵成做的一切:

df.set_index('one').sort_index().groupby('key1')['two'].plot(style='--o', legend=True) 

enter image description here

请注意,截至0.20.3,sorting the index is necessary,图例是a bit wonky