如何在matplotlib上的散点图中添加一个传说(这些点是根据0s和1s的数组编码的)?

发布于 2025-02-12 05:26:36 字数 484 浏览 4 评论 0原文

我在Python 3 Jupyter笔记本上工作。我有一个3列桌子(价格,尺寸和视图)。我创建了一个针对“大小”的“价格”的散点图,但是我根据“视图”列对点进行编码,该列仅包含0s和1s。现在,我想添加一个传说,显示红点表示“无视图”,而蓝点表示“视图”。这是我尝试的:

plt.scatter(data1["size"], data1["price"], c = data1["view"], cmap = "bwr_r")
plt.xlabel("Size", fontsize = 25, c = "green")
plt.ylabel("Price", fontsize = 25, c = "green")
plt.legend(["No view", "View"], bbox_to_anchor= (1.05, 0.5), loc= "lower left")
plt.show()

在运行上面的代码后,除了传说仅显示红点的“无视图”之外,一切正常,蓝点的“视图”没有出现。

I am working in Python 3 Jupyter Notebook. I have a 3-column table (price, size and view). I have created a scatter plot of "price" against "size" but I colour coded the dots according to the "view" column which contains only 0s and 1s. Now I want to add a legend showing the red dots represent "No view" and the blue dots represent "View". This is what I have tried:

plt.scatter(data1["size"], data1["price"], c = data1["view"], cmap = "bwr_r")
plt.xlabel("Size", fontsize = 25, c = "green")
plt.ylabel("Price", fontsize = 25, c = "green")
plt.legend(["No view", "View"], bbox_to_anchor= (1.05, 0.5), loc= "lower left")
plt.show()

After running the code above, everything works fine except the legend only shows "No view" for red dots, "View" for blue dots does not appear.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不即不离 2025-02-19 05:26:36

要完成所需的操作,您需要将视图分配给颜色-0或1,以便映射正确的颜色。这可以使用地图完成。传说的手柄需要添加自定义文本,以便分配蓝色和红色,并使用正确的标签显示。我已经使用随机数作为数据来绘制所需的图,并将您的代码尽可能多地保留。

代码

import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

size = []
price = []
view = []

for i in range(0,100):
    size.append(round(random.random(),3))
    price.append(round(random.random(),3))
    view.append(int(random.random()*10 % 2))
df = pd.DataFrame({'size':size, 'price':price, 'view':view})
colors = {0:'red', 1:'blue'}
plt.scatter(x=df['size'], y=df['price'], c=df['view'].map(colors))
plt.xlabel("Size", fontsize = 25, c = "green")
plt.ylabel("Price", fontsize = 25, c = "green")
markersize=8) for k, v in colors.items()]
custom = [Line2D([], [], marker='.', color='red', linestyle='None'),
          Line2D([], [], marker='.', color='blue', linestyle='None')]

plt.legend(handles = custom, labels=['No View', 'View'], bbox_to_anchor= (1.05, 0.5), loc= "lower left")
plt.show()

输出图

”在此处输入图像描述”

To do what you need, you will need to assign the view - 0 or 1 to a color, so that the right color is mapped. This can be done using map. The handle for the legend will need to have the custom text added, so that the blue and red colors are assigned and show with the correct labels. I have used random numbers as data to plot the graph required, keeping as much of your code as is.

Code

import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

size = []
price = []
view = []

for i in range(0,100):
    size.append(round(random.random(),3))
    price.append(round(random.random(),3))
    view.append(int(random.random()*10 % 2))
df = pd.DataFrame({'size':size, 'price':price, 'view':view})
colors = {0:'red', 1:'blue'}
plt.scatter(x=df['size'], y=df['price'], c=df['view'].map(colors))
plt.xlabel("Size", fontsize = 25, c = "green")
plt.ylabel("Price", fontsize = 25, c = "green")
markersize=8) for k, v in colors.items()]
custom = [Line2D([], [], marker='.', color='red', linestyle='None'),
          Line2D([], [], marker='.', color='blue', linestyle='None')]

plt.legend(handles = custom, labels=['No View', 'View'], bbox_to_anchor= (1.05, 0.5), loc= "lower left")
plt.show()

Output graph

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文