python - 使用 matplotlib 在图例上添加标签不起作用

标签 python python-3.x matplotlib

我有以下数据框

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'var': ['bid', 'on', 'off', 'bid', 'on', 'off'],
                   'aud': ['H', 'H', 'H', 'L', 'L', 'L'],
                   'eff': [0.1, 0.2, 0.3, 0.01, 0.02, 0.03],
                   'spend': [10, 20, 30, 1, 2, 3],
                   'marg': [0.001, 0.002, 0.003, 0.0001, 0.0002, 0.0003]})

我的最终目标是创建一个气泡图,其中每个var具有特定颜色marg 绘图的 y_axis 上的 effx_axis 上的气泡的 size 相等花费颜色尺寸各自的图例

我正在使用以下代码

x = df.loc[df.aud == 'H']['eff']
y = df.loc[df.aud == 'H']['marg']
z = df.loc[df.aud == 'H']['spend']
colours_dict = dict(zip(['bid', 'on', 'off'], ['#185177', '#FAA22C', '#8FC5E8']))

g, ax = plt.subplots()

scatter = ax.scatter(x, y, c=[ colours_dict[i] for i in df.loc[df.aud == 'H']['var'] ], s=z*10)

# produce a legend with the unique colors from the scatter
legend1 = ax.legend(*scatter.legend_elements(),
                    loc="center", title="var")
ax.add_artist(legend1)

# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6)
legend2 = ax.legend(handles, labels, loc="upper right", title="Spend")

plt.savefig('bubbles.png')

问题是带有颜色的图例不显示标签。

有什么帮助吗?

最佳答案

您有两个选择:

手动创建句柄

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'var': ['bid', 'on', 'off', 'bid', 'on', 'off'],
                   'aud': ['H', 'H', 'H', 'L', 'L', 'L'],
                   'eff': [0.1, 0.2, 0.3, 0.01, 0.02, 0.03],
                   'spend': [10, 20, 30, 1, 2, 3],
                   'marg': [0.001, 0.002, 0.003, 0.0001, 0.0002, 0.0003]})

x = df.loc[df.aud == 'H']['eff']
y = df.loc[df.aud == 'H']['marg']
z = df.loc[df.aud == 'H']['spend']
labels = ['bid', 'on', 'off']
colors = ['#185177', '#FAA22C', '#8FC5E8']
colours_dict = dict(zip(labels, colors))

fig, ax = plt.subplots()

c = [colours_dict[i] for i in df.loc[df.aud == 'H']['var']]
scatter = ax.scatter(x, y, c=c, s=z*10)

# produce a legend with the unique colors from the scatter
handles = [plt.Line2D([],[], ls="", marker="o", color=c) for c in colors] 
legend1 = ax.legend(handles, labels, loc="lower right", title="var")

plt.show()

使用颜色映射

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap, BoundaryNorm

df = pd.DataFrame({'var': ['bid', 'on', 'off', 'bid', 'on', 'off'],
                   'aud': ['H', 'H', 'H', 'L', 'L', 'L'],
                   'eff': [0.1, 0.2, 0.3, 0.01, 0.02, 0.03],
                   'spend': [10, 20, 30, 1, 2, 3],
                   'marg': [0.001, 0.002, 0.003, 0.0001, 0.0002, 0.0003]})

x = df.loc[df.aud == 'H']['eff']
y = df.loc[df.aud == 'H']['marg']
z = df.loc[df.aud == 'H']['spend']

labels = ['bid', 'on', 'off',]
colors = ['#185177', '#FAA22C', '#8FC5E8']
inv = [labels.index(i) for i  in df.loc[df.aud == 'H']['var']]

cmap = ListedColormap(colors)
norm = BoundaryNorm(np.arange(len(colors)+1)-0.5, len(colors))

fig, ax = plt.subplots()

scatter = ax.scatter(x, y, c=inv, s=z*10, cmap=cmap, norm=norm)

legend1 = ax.legend(scatter.legend_elements(num=len(labels))[0], labels, 
                    loc="lower right", title="var")

plt.show()

关于python - 使用 matplotlib 在图例上添加标签不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58449082/

相关文章:

python - 如何在 Python 中压缩嵌套循环

python - 在具有共享 x 轴的子图中拟合对数正态分布的直方图

python - 如何在两点之间创建线段?

python - 使用 str.startswith 的高阶函数

javascript - python : disable download popup when using firefox with selenium

python - curses - addstr 文本在较大的终端中不可见

python - 将文本放置在圆圈周围

python - Sklearn 指标值与 Keras 值有很大不同

python - 在正则表达式匹配中提取组

python - Discord.py - 使用命令更改前缀