我正在使用seaborn 的间歇泉数据集制作散点图。我根据“种类”列对点进行着色,但由于某种原因,图例仅显示“长”而忽略了“短”。我不知道我错过了什么。我还想知道是否有一种更简单的方法来对不使用 for 循环的数据进行颜色编码。
geyser_df.head()
duration waiting kind
0 3.600 79 long
1 1.800 54 short
2 3.333 74 long
3 2.283 62 short
4 4.533 85 long
x = geyser_df['waiting']
y = geyser_df['duration']
col = []
for i in range(len(geyser_df)):
if (geyser_df['kind'][i] == 'short'):
col.append('MediumVioletRed')
elif(geyser_df['kind'][i] == 'long'):
col.append('Navy')
plt.scatter(x, y, c=col)
plt.legend(('long','short'))
plt.xlabel('Waiting')
plt.ylabel("Duration")
plt.suptitle("Waiting vs Duration")
plt.show()
pandas.DataFrame.groupby
和 pandas.DataFrame.plot
。python 3.8.12
、pandas 1.3.4
、matplotlib 3.4.3
、seaborn 0.11.2
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# load data
df = sns.load_dataset('geyser')
# plot
fig, ax = plt.subplots(figsize=(6, 4))
colors = {'short': 'MediumVioletRed', 'long': 'Navy'}
for kind, data in df.groupby('kind'):
data.plot(kind='scatter', x='waiting', y='duration', label=kind, color=colors[kind], ax=ax)
ax.set(xlabel='Waiting', ylabel='Duration')
fig.suptitle('Waiting vs Duration')
plt.show()
seaborn
,这是 matplotlib 的高级 API,其中 hue
用于按颜色分隔组。
sns.scatterplot
:轴级图sns.relplot
:图形级绘图,其中 kind='scatter'
是默认绘图样式fig, ax = plt.subplots(figsize=(6, 4))
colors = {'short': 'MediumVioletRed', 'long': 'Navy'}
sns.scatterplot(data=df, x='waiting', y='duration', hue='kind', palette=colors, ax=ax)
ax.set(xlabel='Waiting', ylabel='Duration')
fig.suptitle('Waiting vs Duration')
plt.show()
colors = {'short': 'MediumVioletRed', 'long': 'Navy'}
p = sns.relplot(data=df, x='waiting', y='duration', hue='kind', palette=colors, height=4, aspect=1.5)
ax = p.axes.flat[0] # extract the single subplot axes
ax.set(xlabel='Waiting', ylabel='Duration')
p.fig.suptitle('Waiting vs Duration', y=1.1)
plt.show()
您将
x = geyser_df ['waiting']
和 y = geyser_df ['duration']
作为单个数据集传递,这导致 plt.scatter
仅用作 label="long"
作为图例。我没有足够的使用此类库的经验,但要重现您描述的示例,您需要编写如下程序:
long = [[], []]
short = [[], []]
col=['MediumVioletRed', 'Navy']
for i in range(len(geyser_df["kind"])):
if (geyser_df["kind"][i] == "long"):
long[0].append([geyser_df['waiting'][i]])
long[1].append([geyser_df['duration'][i]])
else:
short[0].append([geyser_df['waiting'][i]])
short[1].append([geyser_df['duration'][i]])
plt.scatter(long[0], long[1], c=col[1], label="long")
plt.scatter(short[0], short[1], c=col[0], label="short")
plt.legend()
plt.xlabel('Waiting')
plt.ylabel("Duration")
plt.suptitle("Waiting vs Duration")
plt.show()