multiple scatter plots with matplotlib and strings on the x-axis.

那年仲夏 提交于 2019-11-28 11:52:41

问题


I'm trying to make three scatter plots in one figure. I tried it this way.

Do an import first.

import matplotlib.pyplot as plt 

Define the variables and make one figure that contains three scatter plots.

c_pop = [0.410, -0.094, -0.111, -0.106, -0.090, 0.070, -0.043, -0.181, 0.221]
c_labels = ['ll120', 'll123', 'll124', 'll27', 'll28', 'll30', 'll446, n12', 'll447, n86', 'll471']
pre_lo = [-0.493]
post_lo = [0.145]
lo_label = ['lo']

fig = plt.figure()
ax1 = fig.add_subplot(111)

ax1.scatter(c_labels, c_pop, color='black')
ax1.scatter(lo_label, pre_lo, color='green', label='pre-SNEP')
ax1.scatter(lo_label, post_lo, color='red', label='post-SNEP')

plt.show()

The error I get is: could not convert string to float: lo

It seems like it tries to convert lo_label into something else.

The code runs if I disable the first scatter plot and only run the second and the third. It also runs when I only run the first scatter plot and disable the second the third.

What is going wrong? Is it possible to make three scatter plots in one plot with labels on the x-axis?


回答1:


Matplotlib categorical support is a rather new feature in matplotlib 2.1. There are some issues which are still being worked on.

Matplotlib >= 2.1.1

The code from the question runs fine in matplotlib 2.1.1 or higher.

import matplotlib.pyplot as plt
import numpy as np 

x1 = ["apple", "banana", "apple", "cherry"]
x2 = ["cherry", "date"]

y1 = [1,2,2,2]
y2 = [3,4]


fig = plt.figure()
ax1 = fig.add_subplot(111)

ax1.scatter(x1, y1, color='black', label='Initial Fruits')
ax1.scatter(x2, y2, color='green', label='Further Fruits')

plt.legend()
plt.show()

Matplotlib <= 2.1.0

While matplotlib 2.1.0 allows in principle to plot categories, it is not possible to add further categories to an existing categorical axes. Hence a solution which would also work for even lower versions would need to be used, plotting the values as numerical data.

import matplotlib.pyplot as plt
import numpy as np 

x1 = ["apple", "banana", "apple", "cherry"]
x2 = ["cherry", "date"]

y1 = [1,2,2,2]
y2 = [3,4]

c = ["black"]*len(x1) + ["green"]*len(x2)
u, inv = np.unique(x1+x2, return_inverse=True)

fig = plt.figure()
ax1 = fig.add_subplot(111)

ax1.scatter(inv, y1+y2, c=c, )

f = lambda c : plt.plot([],color=c, ls="", marker="o")[0]
ax1.legend(handles = [f("black"), f("green")], 
           labels=['Initial Fruits', 'Further Fruits'])

ax1.set_xticks(range(len(u)))
ax1.set_xticklabels(u)

plt.show()

Resulting plot in both cases:



来源:https://stackoverflow.com/questions/48380953/multiple-scatter-plots-with-matplotlib-and-strings-on-the-x-axis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!