简体   繁体   English

matplotlib:根据标签值更改标记颜色

[英]matplotlib: change marker color based on label value

I'm drawing a 3D scatterplot, and intend to give different color to each marker based on the value of y-axis (country) label. 我正在绘制3D散点图,并打算根据y轴(国家/地区)标签的值为每个标记赋予不同的颜色。 I have the following code. 我有以下代码。 The colors of markers aren't what they need to be. 标记的颜色不是必需的。 I think I'm doing something wrong or in-efficient in the for loop. 我认为我在for循环中做错了或效率低下。 Can you point out the mistake that I'm making? 你能指出我犯的错误吗?

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np    

src = ['facebook', 'google', 'amazon','facebook','facebook','google']
year = [2014,2014,2013,2013,2012,2013]
country = ['uk','ru','de','us','uk','us']
avg = [154,267,187,312,274,439]
colors = {'uk' : 'b',
          'de' : 'y',
          'ru' : 'r', 
          'us' : 'c'}

unique_src, idx_src = np.unique(src, return_inverse=True)
unique_cty, idx_cty = np.unique(country, return_inverse=True)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for col, val in zip(colors, country):
    ax.scatter(idx_src, idx_cty, year, s=avg, c=colors[val])
plt.yticks(range(len(unique_cty)), unique_cty, rotation=340)
plt.xticks(range(len(unique_src)), unique_src, rotation=45, horizontalalignment='right')
ax.set_zticks(np.unique(year))
plt.show()

Also, when calling the scatter function, I can't write: 另外,在调用scatter函数时,我无法编写:
ax.scatter(source, country, year, s=avg, c=colors[val])

as I get the following error message: 当我收到以下错误消息:

ValueError: could not convert string to float: facebook ValueError:无法将字符串转换为浮点数:facebook

Why is that so? 为什么会这样? I am using matplotlib version 2.1.2 我正在使用matplotlib版本2.1.2

It seems you want to colorize the points by country. 看来您想按国家/地区对点进行着色。

c = [colors[val] for val in country]
ax.scatter(idx_src, idx_cty, year, s=avg, c=c)

Complete example: 完整的例子:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np    

src = ['facebook', 'google', 'amazon','facebook','facebook','google']
year = [2014,2014,2013,2013,2012,2013]
country = ['uk','ru','de','us','uk','us']
avg = [154,267,187,312,274,439]
colors = {'uk' : 'b',
          'de' : 'y',
          'ru' : 'r', 
          'us' : 'c'}

unique_src, idx_src = np.unique(src, return_inverse=True)
unique_cty, idx_cty = np.unique(country, return_inverse=True)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

c = [colors[val] for val in country]
ax.scatter(idx_src, idx_cty, year, s=avg, c=c)

plt.yticks(range(len(unique_cty)), unique_cty, rotation=340)
plt.xticks(range(len(unique_src)), unique_src, rotation=45, horizontalalignment='right')
ax.set_zticks(np.unique(year))
plt.show()

在此处输入图片说明

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

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