[英]How do I assign different dots different colors in a scatter plot made with MatPlotLib?
Using MatPlotLib and Python, I am making a scatter plot of laptops that has cost on the x-axis and rating on the y-axis. 使用MatPlotLib和Python,我正在制作笔记本电脑的散点图,其中x轴为成本,y轴为评级。 The data is now stored in a tab-separated file. 数据现在存储在制表符分隔文件中。
This link describes MatPlotLib scatter plots. 此链接描述了MatPlotLib散点图。 http://matplotlib.sourceforge.net/examples/api/unicode_minus.html http://matplotlib.sourceforge.net/examples/api/unicode_minus.html
Each laptop's brand is Lenova, HP, or Dell. 每台笔记本电脑的品牌都是Lenova,HP或戴尔。 I want to assign different colors for dots representing laptops of each brand. 我想为代表每个品牌的笔记本电脑的点分配不同的颜色。 For instance, Dell laptops are marked by a blue point, while Lenova laptops are represented by a red point. 例如,戴尔笔记本电脑标有蓝点,而Lenova笔记本电脑标有红点。
How can I do that? 我怎样才能做到这一点?
A better example for you would be the scatter plot example . 更好的例子是散点图示例 。
In your case, in place of the close
array, you want some array of strings that are one of 'r'
, 'g'
, or 'b'
. 在您的情况下,您需要一些'r'
, 'g'
或'b'
之一的字符串数组来代替close
数组。 So if you can read an array of the brands, you can then translate that into an array of those characters. 因此,如果您可以阅读一系列品牌,则可以将其转换为这些字符的数组。 (And I guess you don't want the equivalent of the volume
array, which makes the circles different sizes.) (我想你不想要相当于volume
数组,这会使圆圈的大小不同。)
You could translate your brand
array to colors with something like 您可以将您的brand
阵列转换为类似的颜色
brandcolors = [brand[i].replace('HP','g').replace('Lenovo','r').replace('Dell','b') for i in range(len(brand))]
Then, the plotting function would look like 然后,绘图功能看起来像
scatter(cost, rating, c=brandcolors)
Adding a legend gets a little tricky. 添加图例有点棘手。 The matplotlib docs suggest using a "proxy artist", where you create something, but don't put it on the plot. matplotlib文档建议使用“代理艺术家”,在那里你创建一些东西,但不要把它放在情节上。 For example: 例如:
pr = Rectangle((0, 0), 1, 1, fc='r')
pg = Rectangle((0, 0), 1, 1, fc='g')
pb = Rectangle((0, 0), 1, 1, fc='b')
legend([pr, pg, pb], ['Lenovo', 'HP', 'Dell'])
That's a little ugly because it comes out as a rectangle regardless of the dot shape. 这有点难看,因为无论点的形状如何,它都是一个矩形。 The other possible hack is to actually plot a single dot, but make sure it stays off the plot area. 另一个可能的黑客是实际绘制一个点,但要确保它保持在绘图区域之外。
plot([-100], 'ro', label='Lenovo')
...
ax.set_ylim(bottom=0)
legend()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.