问题描述
是否可以在散点图的大小与某些数据成比例的散点图中添加辅助图例?
Is there a way to add a secondary legend to a scatterplot, where the size of the scatter is proportional to some data?
我写了下面的代码来生成散点图.散点图的颜色表示年份(取自用户定义的df),散点图的大小表示变量3(也取自df,但是原始数据):
I have written the following code that generates a scatterplot. The color of the scatter represents the year (and is taken from a user-defined df) while the size of the scatter represents variable 3 (also taken from a df but is raw data):
import pandas as pd
colors = pd.DataFrame({'1985':'red','1990':'b','1995':'k','2000':'g','2005':'m','2010':'y'}, index=[0,1,2,3,4,5])
fig = plt.figure()
ax = fig.add_subplot(111)
for i in df.keys():
df[i].plot(kind='scatter',x='variable1',y='variable2',ax=ax,label=i,s=df[i]['variable3']/100, c=colors[i])
ax.legend(loc='upper right')
ax.set_xlabel("Variable 1")
ax.set_ylabel("Variable 2")
此代码(包含我的数据)产生以下图形:
This code (with my data) produces the following graph:
因此,虽然对颜色/年份进行了清晰明确的定义,但分散的大小却没有.
So while the colors/years are well and clearly defined, the size of the scatter is not.
如何添加辅助图例或附加图例,以定义散点图的含义?
How can I add a secondary or additional legend that defines what the size of the scatter means?
推荐答案
您将需要自己创建第二个图例,即您需要创建一些艺术家来填充图例.对于散点图,我们可以使用普通的plot
并相应地设置标记.在下面的示例中显示.要实际添加第二个图例,我们需要在轴上添加第一个图例,以使新的图例不会覆盖第一个图例.
You will need to create the second legend yourself, i.e. you need to create some artists to populate the legend with. In the case of a scatter we can use a normal plot
and set the marker accordingly.This is shown in the below example. To actually add a second legend we need to add the first legend to the axes, such that the new legend does not overwrite the first one.
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np; np.random.seed(1)
import pandas as pd
plt.rcParams["figure.subplot.right"] = 0.8
v = np.random.rand(30,4)
v[:,2] = np.random.choice(np.arange(1980,2015,5), size=30)
v[:,3] = np.random.randint(5,13,size=30)
df= pd.DataFrame(v, columns=["x","y","year","quality"])
df.year = df.year.values.astype(int)
fig, ax = plt.subplots()
for i, (name, dff) in enumerate(df.groupby("year")):
c = matplotlib.colors.to_hex(plt.cm.jet(i/7.))
dff.plot(kind='scatter',x='x',y='y', label=name, c=c,
s=dff.quality**2, ax=ax)
leg = plt.legend(loc=(1.03,0), title="Year")
ax.add_artist(leg)
h = [plt.plot([],[], color="gray", marker="o", ms=i, ls="")[0] for i in range(5,13)]
plt.legend(handles=h, labels=range(5,13),loc=(1.03,0.5), title="Quality")
plt.show()
这篇关于向散点图添加第二个图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!