0

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?

0

1 Answer 1

4

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:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.