[英]How to scatter plot each group of a pandas DataFrame
我正在使用來自 seaborn 的間歇泉數據集制作散點圖。 我正在根據“種類”列對點進行着色,但出於某種原因,圖例僅顯示“長”而未顯示“短”。 我不知道我錯過了什么。 我還想知道是否有一種更簡單的方法來對不使用 for 循環的數據進行顏色編碼。 謝謝!
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()
您將x = geyser_df ['waiting']
和y = geyser_df ['duration']
作為單個數據集plt.scatter
,這導致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()
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.