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

China☆狼群 提交于 2019-11-29 18:13:52
ImportanceOfBeingErnest

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:

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