简体   繁体   English

当图例只是数值时,如何使用pyplot.scatter()绘制图例?

[英]How does one plot the legend with pyplot.scatter(), when the legend are only numerical values?

I cannot see to find (or figure out) how to show the legend using pyplot.scatter() when I've changed the labels to be numerical values. 当我将标签更改为数值时,我无法找到(或弄清楚)如何使用pyplot.scatter()显示图例。

That is, I transformed my categorical values 'a', 'b', 'c', .. into 0, 1, 2, ... 也就是说,我将我的分类值'a','b','c',...转换为0,1,2,......

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter

Here is the example given on the URL above: 以下是上面URL中给出的示例:

import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2  # 0 to 15 point radii

plt.scatter(x, y, s=area, c=colors, alpha=0.5, cmap=cm.jet)
plt.show()

which outputs 哪个输出 在此输入图像描述

Normally, I believe one would do something like this: 通常情况下,我相信有人会这样做:

example = plt.scatter(x, y, s=area, c=colors, alpha=0.5, cmap=cm.jet)
plt.legend(handles=[example])
plt.show()

This does not output a legend corresponding each color in the plot with the number in the array. 这不会输出与图中每个颜色对应的图例,其中数字与数组中的数字相对应。

/opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/matplotlib/axes/_axes.py:518: UserWarning: The handle <matplotlib.collections.PathCollection object at 0x1167d03c8> has a label of '_collection0' which cannot be automatically added to the legend.
  'legend.'.format(handle, label))

How can I output a legend which shows which number corresponds with the array value? 如何输出显示哪个数字与数组值对应的图例?

A legend won't work for your scatter plot because the scatter plot creates a single object and would only appear as a single item in a legend . legend不适用于散点图,因为散点图会创建单个对象,并且只会在legend显示为单个项目。 Since the color of each point depends upon the colormap of the axes, you'll instead need to use a colorbar 由于每个点的颜色取决于轴的颜色表,你反而需要使用colorbar

plt.colorbar(example)

If you want a legend instead, you need to create a separate scatter plot for each group and then create a legend from that . 如果你想有一个legend相反,你需要为每个组创建一个单独的散点图,然后创建一个传奇。 An example of that is shown here 这里显示一个例子

This is what I personally use for all of my matplotlib legends. 这是我个人用于所有matplotlib传说的内容。 I usually store my data in dictionaries and pd.Series objects. 我通常将我的数据存储在dictionariespd.Series对象中。

def get_legend_markers(D_label_color, marker="o", marker_kws={"linestyle":""}):
    """
    Usage: plt.legend(*legend_vars(D_taxon_color),
                      loc="lower center",
                      bbox_to_anchor=(0.5,-0.15),
                      fancybox=True, shadow=True,
                      prop={'size':15})

    Input: Dictionary object of {label:color}
    Output: Tuple of markers and labels
    """
    markers = [plt.Line2D([0,0],[0,0],color=color, marker=marker, **marker_kws) for color in D_label_color.values()]
    return (markers, D_label_color.keys())

So you could something like: 所以你可以这样:

D_label_color = {"A":"green", "B":"blue", "C":"red"}
fig, ax = plt.subplots()
x = np.linspace(0, 2*np.pi)
y = np.sin(x)
c = ["green"]*20 + ["blue"]*20 + ["red"]*10
ax.scatter(x=x, y=y, c=c)
ax.legend(*get_legend_markers(D_label_color)

If you don't know exactly which color is assigned to which point you can assign them with seaborn using sns.color_palette(n_colors) for each category and then make a list/vector of colors ( like c above ) and then give ax.scatter that color assignment. 如果您seaborn地知道哪个颜色分配到哪个点,您可以使用sns.color_palette(n_colors)为每个类别分配seaborn ,然后制作颜色列表/矢量(如上面的c ),然后给出ax.scatter那个颜色分配。 Hope this helps. 希望这可以帮助。 If you're dealing with continuous data then i would go with a color bar like @suever mentioned above. 如果你正在处理连续数据,那么我会使用像上面提到的@suever这样的颜色条。 You can't really have a legend with continuous data. 你不可能拥有连续数据的传奇。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM