如何散点图pandas DataFrame的每组

问题描述 投票:0回答:2

我正在使用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()

python pandas matplotlib visualization scatter-plot
2个回答
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
    用于按颜色分隔组。
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()

1
投票

 您将

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

© www.soinside.com 2019 - 2024. All rights reserved.