python - 如何创建基于多种颜色的图例?

标签 python matplotlib

我目前有一张系外行星日照与密度的图表,不同的颜色代表不同的轨道周期。我已经弄清楚了颜色情况,我只是对如何设置图例感到困惑。这是我所拥有的。

plt.figure(figsize = (9,7))
plt.title('Insolation vs Density', fontsize = 24, 
fontweight='bold')
plt.xlabel('Density [g/cm$^3$]', fontsize = 16)
plt.ylabel('Insolation [Earth Flux]', fontsize=16)
plt.xscale('log')
plt.yscale('log')
x = data['Density [g/cm**3]']
y = data['Insolation [Earth Flux]']
z = data['Orbital Period']

def pltcolor(lst):
    cols=[]
    for i in data['Orbital Period']:
        if i <= 3:
            cols.append('mediumturquoise'),
        elif i >= 20 :
            cols.append('blue'),
        else:
            cols.append('crimson')
    return cols
cols=pltcolor(z)

plt.scatter(x=x,y=y,c=cols)
plt.scatter(circum_data['Density [g/cm**3]'],circum_data['Insolation [Earth Flux]'], color = 'fuchsia', label = 
Circumbinary Planets')
plt.legend();

最佳答案

根据我的理解,您需要为每个组调用plt.scatter。作为引用,请查看此 question 。现在,您正在计算每个数据点的颜色应该是什么,然后在 cols 中为它们分配颜色。然后,您调用 plt.scatter 一次,它会绘制所有点并相应地分配颜色。然而,matplotlib 仍然认为所有这些点都来自同一组。因此,当您调用 plt.legend() 时,它只会给出一个标签。

我尝试使用您的代码为您解决问题。这有点棘手,因为您从示例中删除了数据(可以理解)。我假设您的数据是一个列表,因此创建了一些假数据来测试我的方法。

所以我的方法如下:检查您的数据,如果您的 z 数据位于特定范围内,则将其分配给一个新数组。处理完该组(z 范围)的所有数据后,将其绘制出来。然后对每组重复此操作。我在下面附上了我的想法的示例。可能有更清洁的方法可以做到这一点。但是,总体方法是相同的。尝试单独绘制每个组的图。

import matplotlib.pyplot as plt
import math

# Fake data I created
data = {}
data['Density [g/cm**3]'] = [10,15, 31, 24,55]
data['Insolation [Earth Flux]'] = [10,15,8,4,55]
data['Orbital Period'] = [10,15,3,2,55]

circum_data = {}
circum_data['Density [g/cm**3]'] = [10,15,7,5,55]
circum_data['Insolation [Earth Flux]'] = [10,15,4,3,55]

# ----- Your code------
plt.figure(figsize = (9,7))
plt.title('Insolation vs Density', fontsize = 24, fontweight='bold')
plt.xlabel('Density [g/cm$^3$]', fontsize = 16)
plt.ylabel('Insolation [Earth Flux]', fontsize=16)
plt.xscale('log')
plt.yscale('log')
x = data['Density [g/cm**3]']
y = data['Insolation [Earth Flux]']
z = data['Orbital Period']
# -----------------

# Created the ranges you want
distances_max = [3, 20, math.inf]
distances_min = [-1*math.inf, 3, 20]
# Select you colors
colors = ['mediumturquoise', 'blue', 'crimson']
# The legend names you want
names = ['name1', 'name2', 'name3']

# For each of the ranges
for i in range(len(names)):
    # Create a new group of data
    col = []
    data_x = []
    data_y = []
    # Go through your data and put it in the group if it is inside the range
    for (xi, yi, zi) in zip(x, y, z): 
        if distances_min[i] < zi <= distances_max[i]:
            col.append(colors[i])
            data_x.append(xi) 
            data_y.append(yi) 

    # Plot the group of data
    plt.scatter(x=data_x,y=data_y,c=colors[i], label=names[i])   


# plt.scatter(circum_data['Density [g/cm**3]'],
#             circum_data['Insolation [Earth Flux]'],
#             color = 'fuchsia',
#             label ='Circumbinary Planets')
plt.legend()
plt.show()

运行此代码会产生以下输出,其中 name1、name2、name3 在 names 列表中定义。

Example graph

我希望这有帮助。祝你好运!

关于python - 如何创建基于多种颜色的图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56712369/

相关文章:

python - 使用 3d 子图设置 matplotlib 图的大小

python - 无法使用 Qt5Agg 后端渲染 matplotlib 图形

python - 使用不同的 y 轴绘制 pandas 数据框中的条形图和线条

python - 气象站项目中的KeyError

python - pygame中的平滑运动

python - 从具有两个唯一值的 Pandas 系列返回相反的值

python - 从指定的 x/y 值填充直方图

python - python,matplotlib:谱图数据数组值与谱图图不匹配

python - Plotly 值错误 - 颜色属性无效

python - 多个 Try/Except block