【发布时间】:2020-01-27 15:01:50
【问题描述】:
我有几个散点图,每个散点图都有不同的类。我想将它们全部粘贴在 kx2 网格中,并在包含所有当前类的一侧带有一个图例,例如从单个图中删除图例。
我该怎么做?
这是 2x2 测试的 4 个图
from matplotlib.lines import Line2D
import pandas as pd
import seaborn as sns; sns.set()
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
df1 = pd.DataFrame({
"class":["a", "b", "e"],
"time":[1,2,3],
"score":[10, 20, 30]
})
df2 = pd.DataFrame({
"class":["a", "c", "d"],
"time":[0,5,10],
"score":[5, 25, 30]
})
df3 = pd.DataFrame({
"class":["a", "b", "c", "d", "e"],
"time":[0,5,10,30,50],
"score":[5, 25, 30, 40, 100]
})
df4 = pd.DataFrame({
"class":["a", "e"],
"time":[1,2],
"score":[10,25]
})
def get_palette():
pal = {
'a': "#4C72B0",
'b': "#55A868",
'c': "#C44E52",
'd': "#8172B2",
'e': "#CCB974",
}
return pal
def get_markers():
mark = {
'a': Line2D.filled_markers[0],
'b': Line2D.filled_markers[5],
'c': Line2D.filled_markers[6],
'd': Line2D.filled_markers[7],
'e': Line2D.filled_markers[8],
}
return mark
def get_scatterplot(source, ds_name):
scatter = sns.scatterplot(palette=get_palette(), markers=get_markers(),
edgecolor='black', alpha=0.6, x="score", y="time",
hue="class", style="class", s=150,
data=source).set_title(ds_name)
return scatter
scatter_df1 = get_scatterplot(df1, "df1")
plt.show()
scatter_df2 = get_scatterplot(df2, "df2")
plt.show()
scatter_df3 = get_scatterplot(df3, "df3")
plt.show()
scatter_df4 = get_scatterplot(df4, "df4")
plt.show()
这是我根据 Stack 上的其他一些响应尝试做的事情
fig, axs = plt.subplots(ncols=2, nrows=2)
sns.scatterplot(palette=get_palette(), markers=get_markers(), edgecolor='black', alpha=0.6, x="score", y="time", hue="class", style="class", s=150, data=df1, ax=axs[0]).set_title("ds1")
sns.scatterplot(palette=get_palette(), markers=get_markers(), edgecolor='black', alpha=0.6, x="score", y="time", hue="class", style="class", s=150, data=df2, ax=axs[1]).set_title("ds2")
sns.scatterplot(palette=get_palette(), markers=get_markers(), edgecolor='black', alpha=0.6, x="score", y="time", hue="class", style="class", s=150, data=df3, ax=axs[2]).set_title("ds3")
sns.scatterplot(palette=get_palette(), markers=get_markers(), edgecolor='black', alpha=0.6, x="score", y="time", hue="class", style="class", s=150, data=df4, ax=axs[3]).set_title("ds4")
但它出错了,不知道为什么......
AttributeError: 'numpy.ndarray' object has no attribute 'scatter'
【问题讨论】:
-
您可以使用自定义
figlegend来获取整个图的单个图例,但您必须处理类重复项(即创建一个类名数组并使用np.unique) .这足以满足您的目的吗? -
我对类重复有点困惑......你能回答一个答案,以便澄清事情并且我可以接受吗?我对此真的很陌生,所以这个提示没有多大帮助:(谢谢!
-
@WilliamMiller 我也添加了我的尝试,但我不知道它是接近正确还是完全错过
-
您在编辑中遇到的错误是由于您从
axs访问轴的方式。fig, axs = plt.subplots(nrows, ncols)返回一个由axes实例组成的数组,其形状为(nrows, ncols),因此您需要执行axs[i, j]来检索单个axes实例(请参阅this answer)
标签: python pandas matplotlib seaborn