0

我正在绘制一个 3D 散点图,并打算根据 y 轴(国家)标签的值为每个标记赋予不同的颜色。我有以下代码。标记的颜色不是它们需要的颜色。我认为我在 for 循环中做错了什么或效率低下。你能指出我犯的错误吗?

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()

另外,在调用 scatter 函数时,我不能写:
ax.scatter(source, country, year, s=avg, c=colors[val])

因为我收到以下错误消息:

ValueError:无法将字符串转换为浮点数:facebook

为什么呢?我正在使用 matplotlib 2.1.2 版

4

1 回答 1

2

看来您想按国家/地区对点进行着色。

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

完整示例:

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()

在此处输入图像描述

于 2018-01-30T10:54:27.087 回答