matplotlib 如何按类别创建散点图[重复]

piah890a  于 2023-05-01  发布在  其他
关注(0)|答案(8)|浏览(126)

此问题已在此处有答案

Color a scatter plot by Column Values(6个回答)
1年前关闭。
我试图使用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.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()
rmbxnbpk

rmbxnbpk1#

seaborn有一个 Package 器函数scatterplot,它可以更有效地完成这一任务。

sns.scatterplot(data = df, x = 'one', y = 'two', data =  'key1'])
vxf3dgd4

vxf3dgd42#

您可以使用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()

如果您希望事情看起来像默认的pandas样式,那么只需使用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()

piwo6bdm

piwo6bdm3#

使用Seabornpip install seaborn)作为一个链接很容易做到这一点
sns.scatterplot(x_vars="one", y_vars="two", data=df, hue="key1")

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.scatterplot(x="one", y="two", data=df, hue="key1")

下面是数据框供参考:

由于数据中有三个变量列,您可能需要使用以下命令绘制所有成对维度:

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

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

uhry853o

uhry853o4#

对于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)

结果是:

iaqfqrcu

iaqfqrcu5#

你可以使用df。plot.scatter,并将一个数组传递给c= argument,定义每个点的颜色:

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()

qrjkbowd

qrjkbowd6#

从matplotlib 3.1以后可以使用.legend_elements()。自动图例创建中显示了一个示例。优点是可以使用单个分散调用。
在这种情况下:

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()

wbgh16ku

wbgh16ku7#

您也可以尝试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')

ggplot代码

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

dzjeubhm

dzjeubhm8#

这是相当黑客,但你可以使用one1作为一个Float64Index来完成所有的事情:

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

请注意,从0。20.3,sorting the index is necessary,图例为a bit wonky

相关问题