Python Pandas/Pyplot中的散点图:如何按类别绘制
我正在尝试使用Pandas DataFrame对象在pyplot中绘制一个简单的散点图,但我希望能够高效地绘制两个变量,但符号由第三列(键)指示。我尝试过使用df.groupby的各种方法,但没有成功。下面是一个示例df脚本。这将根据“key1”为标记着色,但我希望看到带有“key1”类别的图例。我接近了吗?谢谢Python Pandas/Pyplot中的散点图:如何按类别绘制,python,matplotlib,pandas,Python,Matplotlib,Pandas,我正在尝试使用Pandas DataFrame对象在pyplot中绘制一个简单的散点图,但我希望能够高效地绘制两个变量,但符号由第三列(键)指示。我尝试过使用df.groupby的各种方法,但没有成功。下面是一个示例df脚本。这将根据“key1”为标记着色,但我希望看到带有“key1”类别的图例。我接近了吗?谢谢 import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame(np.
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()
使用
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)
结果是:
您可以使用
分散
进行此操作,但这需要为键1
设置数值,并且您不会有图例,正如您所注意到的那样
对于这样的离散类别,最好只使用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()
如果您希望事情看起来像默认的pandas
样式,那么只需使用pandas样式表更新rcParams
,并使用其颜色生成器即可。(我还稍微调整了图例):
这是一个简单的操作(pip install seaborn
)作为一体机
sns.scatterplot(x_vars=“one”,y_vars=“two”,data=df,hue=“key1”)
:
以下是供参考的数据框:
由于您的数据中有三个变量列,因此您可能希望使用以下方式绘制所有成对维度:
sns.pairplot(vars=["one","two","three"], data=df, hue="key1")
是另一种选择。您也可以尝试或使用侧重于声明性可视化的方法
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))
牵牛星代码
ggplot代码
您可以使用df.plot.scatter,并将数组传递给定义每个点颜色的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()
它相当粗糙,但您可以使用
one1
作为Float64Index
一次完成所有操作:
df.set_index('one').sort_index().groupby('key1')['two'].plot(style='--o', legend=True)
请注意,从0.20.3开始,图例为。从matplotlib 3.1开始,您可以使用。示例如所示。优点是可以使用单个分散调用 在这种情况下:
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)
fig, ax = plt.subplots()
sc = ax.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)
ax.legend(*sc.legend_elements())
plt.show()
如果钥匙不是直接以数字的形式给出的,它看起来就像
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'] = list("AAABBBCCCC")
labels, index = np.unique(df["key1"], return_inverse=True)
fig, ax = plt.subplots()
sc = ax.scatter(df['one'], df['two'], marker = 'o', c = index, alpha = 0.8)
ax.legend(sc.legend_elements()[0], labels)
plt.show()
seaborn有一个包装函数
scatterplot
,可以更有效地完成这项工作
sns.scatterplot(data = df, x = 'one', y = 'two', data = 'key1'])
为什么在上面的RGB示例中,图例中会显示两次符号?如何仅显示一次?@SteveSchulist-使用
ax.legend(numpoints=1)
仅显示一个标记。有两个,与Line2D
一样,通常有一条线连接两个标记。此代码仅在ax.plot()
命令后添加plt.hold(True)
后对我有效。知道为什么吗?set\u color\u cycle()
在matplotlib 1.5中被弃用了。现在有set\u prop\u cycle()
。我得到一个错误,说“PathCollection”对象没有“legends\u elements”属性。我的代码如下<代码>图,ax=plt.子图(1,1,figsize=(4,4))scat=ax.散射(rand_jitter(重要数据帧[“训练类型”\u int],抖动=0.04),重要数据帧[“距离”],c=颜色列表,标记='o',alpha=0.9)打印(scat.图例_元素())\ax.图例(*scat.图例(@NandishPatel检查答案的第一句话。还要确保不要混淆图例元素
和图例元素
。是的,谢谢。那是一个打字错误(图例/图例)。在过去的6个小时里我一直在做一些事情,所以我没有想到Matplotlib版本。我以为我用的是最新的。我很困惑,文档中说有这样的方法,但代码给出了一个错误。再次感谢你。我现在可以睡觉了。
df.set_index('one').sort_index().groupby('key1')['two'].plot(style='--o', legend=True)
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)
fig, ax = plt.subplots()
sc = ax.scatter(df['one'], df['two'], marker = 'o', c = df['key1'], alpha = 0.8)
ax.legend(*sc.legend_elements())
plt.show()
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'] = list("AAABBBCCCC")
labels, index = np.unique(df["key1"], return_inverse=True)
fig, ax = plt.subplots()
sc = ax.scatter(df['one'], df['two'], marker = 'o', c = index, alpha = 0.8)
ax.legend(sc.legend_elements()[0], labels)
plt.show()
sns.scatterplot(data = df, x = 'one', y = 'two', data = 'key1'])