Shaun
Shaun

Reputation: 531

Plot dictionary with multiple values in different colors

Is there a way to plot a dictionary with multiple values with different colors? Let's say we have a dictionary:

d = {"alpha": [1,2,3,4], "beta": [5,6,7,8]}

How could one plot alpha[0], beta[0] ... blue and alpha[1], beta[1] .... yellow etc?

Let's say that the values are on y-axis and the keys on the x-axis. My code would look like this:

x_multi = []
y_multi = []
for k, v in data_all_bands.iteritems():
    x_multi.extend(list(itertools.repeat(int(k[-3:]), len(v))))
    y_multi.extend(v)

plt_multi = axes[0].scatter(x_multi, y_multi)

where data_all_bands looks like this:

2016050 [4.2958281793198241, 3.7025449821599157, 5.1717757645735025, 4.9954723025001719]
2016178 [4.0679016016577032, 2.890807214158575, 4.9627629940324081, 4.8505350289087952]
2016290 [3.6947496139720259, 3.1549071645707891, 4.5131724769284824, 4.4082219917836483]

Upvotes: 0

Views: 761

Answers (1)

Sheldore
Sheldore

Reputation: 39052

Following is one way using a list of pre-assigned colors of your choice and plotting the values of each key in a different color. This way you don't need to define any empty lists x_multi and y_multi.

fig = plt.figure()
ax = fig.add_subplot(111)
colors = ['blue', 'yellow', 'green']
i = 0
for k, v in data_all_bands.items():
    x_multi = list(itertools.repeat(int(k[-3:]), len(v)))
    plt_multi = ax.scatter(x_multi, v, color=colors[i])
    i += 1

enter image description here

Way 2 since it is unclear what order of colors you want

x_multi = [int(k[-3:]) for k in data_all_bands.keys()] 
colors = ['blue', 'yellow', 'green', 'red']

for i in range(len(list(data_all_bands.values())[0])):
    y_multi = [v[i] for v in data_all_bands.values()]
    plt_multi = ax.scatter(x_multi, y_multi, color=colors[i])

enter image description here

Upvotes: 1

Related Questions