同一散点图上的两个或更多数量
Two or more quantities on same scatter plot seaborn
我正在尝试为以下数据绘制散点图,所有列都在一个图中。
实际上我从 csv 文件导入了这些数据并保存在数据框中 df_inv
然后我将它保存在变量提示中
tips = df_inv
sns.scatterplot(data=tips, x=df_inv.index, y = "a")
plt.show()
我想在同一个图上添加 b、c 和 d 列,但找不到正确的代码。我试过 y = ["a", "b", "c", "d", "e"]
但没用。我希望我的结果采用以下格式,理想情况下不是所有圆圈,而是一些 x、* 和其他形状。
请帮我完成目标。
您可以使用 pandas.melt
:
在不同的数据框中重新调整数据
df_inv = df_inv.reset_index()
columns = ['index', 'a', 'b', 'c', 'd']
df_to_plot = df_inv[columns]
df_to_plot = pd.melt(frame = df_to_plot,
id_vars = 'index',
var_name = 'column_name',
value_name = 'value')
这样,你会得到类似的东西:
index column_name value
0 0 a 315
1 1 a 175
2 2 a 65
3 3 a 370
4 4 a 419
5 0 b 173
6 1 b 206
7 2 b 271
8 3 b 463
9 4 b 419
10 0 c 58
...
现在你终于可以用一行代码绘图了:
sns.scatterplot(ax = ax, data = df_to_plot, x = 'index', y = 'value', style = 'column_name', hue = 'column_name')
完整代码
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
N = 5
df_inv = pd.DataFrame()
df_inv['a'] = np.random.randint(low = 50, high = 500, size = N)
df_inv['b'] = np.random.randint(low = 50, high = 500, size = N)
df_inv['c'] = np.random.randint(low = 50, high = 500, size = N)
df_inv['d'] = np.random.randint(low = 50, high = 500, size = N)
df_inv = df_inv.reset_index()
columns = ['index', 'a', 'b', 'c', 'd']
df_to_plot = df_inv[columns]
df_to_plot = pd.melt(frame = df_to_plot,
id_vars = 'index',
var_name = 'column_name',
value_name = 'value')
fig, ax = plt.subplots()
sns.scatterplot(ax = ax, data = df_to_plot, x = 'index', y = 'value', style = 'column_name', hue = 'column_name')
plt.show()
另一种解决方案,如果您不想重塑数据框,将多次调用 sns.scatterplot,每次使用您想要在 y 参数中绘制的不同列。然后,每一列将绘制在第一次调用将生成的相同轴上。您可以创建每次调用时使用的颜色和标记列表,也可以手动创建图例。
这是示例代码,使用 df_inv 数据框中的所有列(带有一些随机生成的数据)。
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import random
import matplotlib.lines as mlines
df_inv = pd.DataFrame({'a': random.sample(range(300, 400), 5),
'b': random.sample(range(100, 200), 5),
'c': random.sample(range(40, 90), 5)},
index=range(1,6))
markers = ['o', 'x', 'd']
colors = ['purple', 'cyan', 'green']
legend_handles = []
for i, col_name in enumerate(df_inv.columns):
sns.scatterplot(data=df_inv, x=df_inv.index, y=col_name,
marker=markers[i], color=colors[i], s=100) # s = marker size
legend_handles.append(mlines.Line2D([], [], color=colors[i], marker=markers[i],
linestyle='None', markersize=8, label=col_name))
plt.ylabel('Value')
plt.xlabel('Index')
plt.grid()
plt.legend(handles=legend_handles, bbox_to_anchor=(1.02, 1), title='Column')
plt.tight_layout()
plt.show()
代码结果:
我正在尝试为以下数据绘制散点图,所有列都在一个图中。
实际上我从 csv 文件导入了这些数据并保存在数据框中 df_inv
然后我将它保存在变量提示中
tips = df_inv
sns.scatterplot(data=tips, x=df_inv.index, y = "a")
plt.show()
我想在同一个图上添加 b、c 和 d 列,但找不到正确的代码。我试过 y = ["a", "b", "c", "d", "e"]
但没用。我希望我的结果采用以下格式,理想情况下不是所有圆圈,而是一些 x、* 和其他形状。
请帮我完成目标。
您可以使用 pandas.melt
:
df_inv = df_inv.reset_index()
columns = ['index', 'a', 'b', 'c', 'd']
df_to_plot = df_inv[columns]
df_to_plot = pd.melt(frame = df_to_plot,
id_vars = 'index',
var_name = 'column_name',
value_name = 'value')
这样,你会得到类似的东西:
index column_name value
0 0 a 315
1 1 a 175
2 2 a 65
3 3 a 370
4 4 a 419
5 0 b 173
6 1 b 206
7 2 b 271
8 3 b 463
9 4 b 419
10 0 c 58
...
现在你终于可以用一行代码绘图了:
sns.scatterplot(ax = ax, data = df_to_plot, x = 'index', y = 'value', style = 'column_name', hue = 'column_name')
完整代码
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
N = 5
df_inv = pd.DataFrame()
df_inv['a'] = np.random.randint(low = 50, high = 500, size = N)
df_inv['b'] = np.random.randint(low = 50, high = 500, size = N)
df_inv['c'] = np.random.randint(low = 50, high = 500, size = N)
df_inv['d'] = np.random.randint(low = 50, high = 500, size = N)
df_inv = df_inv.reset_index()
columns = ['index', 'a', 'b', 'c', 'd']
df_to_plot = df_inv[columns]
df_to_plot = pd.melt(frame = df_to_plot,
id_vars = 'index',
var_name = 'column_name',
value_name = 'value')
fig, ax = plt.subplots()
sns.scatterplot(ax = ax, data = df_to_plot, x = 'index', y = 'value', style = 'column_name', hue = 'column_name')
plt.show()
另一种解决方案,如果您不想重塑数据框,将多次调用 sns.scatterplot,每次使用您想要在 y 参数中绘制的不同列。然后,每一列将绘制在第一次调用将生成的相同轴上。您可以创建每次调用时使用的颜色和标记列表,也可以手动创建图例。 这是示例代码,使用 df_inv 数据框中的所有列(带有一些随机生成的数据)。
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import random
import matplotlib.lines as mlines
df_inv = pd.DataFrame({'a': random.sample(range(300, 400), 5),
'b': random.sample(range(100, 200), 5),
'c': random.sample(range(40, 90), 5)},
index=range(1,6))
markers = ['o', 'x', 'd']
colors = ['purple', 'cyan', 'green']
legend_handles = []
for i, col_name in enumerate(df_inv.columns):
sns.scatterplot(data=df_inv, x=df_inv.index, y=col_name,
marker=markers[i], color=colors[i], s=100) # s = marker size
legend_handles.append(mlines.Line2D([], [], color=colors[i], marker=markers[i],
linestyle='None', markersize=8, label=col_name))
plt.ylabel('Value')
plt.xlabel('Index')
plt.grid()
plt.legend(handles=legend_handles, bbox_to_anchor=(1.02, 1), title='Column')
plt.tight_layout()
plt.show()
代码结果: