Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib scatterplot x axis labels

Tags:

When I'm adding the c option to a scatterplot in matplotlib, the x axis labels dissapear. Here's an example: https://github.com/Kornel/scatterplot-matplotlib/blob/master/Scatter%20plot%20x%20axis%20labels.ipynb (pull requests are welcome:))

Here's the same example as in the notebook:

import pandas as pd
import matplotlib.pyplot as plt


test_df = pd.DataFrame({
        "X": [1, 2, 3, 4],
        "Y": [5, 4, 2, 1],
        "C": [1, 2, 3, 4]
    })

Now compare the result of:

test_df.plot(kind="scatter", x="X", y="Y", s=50);

here the x axis labels are present

To:

test_df.plot(kind="scatter", x="X", y="Y", c="C");

enter image description here

Where are the x axis labels? Is this a feature I'm missing?

Pandas version: 0.18.1 Matplotlib: 1.5.3 Python: 3.5.2

Thanks for any help, Kornel

EDIT: The solution as pointed out by @Kewl is to call plt.subplots and specify the axes:

fig, ax = plt.subplots()
test_df.plot(kind="scatter", x="X", y="Y", s=50, c="C", cmap="plasma", ax=ax);

gives

solved

P.S. It looks like a jupyter issue, the label is fine when called without a jupyter notebook

like image 997
CatInABox Avatar asked Mar 30 '17 15:03

CatInABox


People also ask

How do you change the x-axis label in Matplotlib?

MatPlotLib with Python Using subplot() method, add a subplot to the current figure. Plot x and log(x) using plot() method. Set the label on X-axis using set_label() method, with fontsize=16, loc=left, and color=red. To set the xlabel at the end of X-axis, use the coordinates, x and y.

How do you add x-axis labels in python?

Create Labels for a Plot With Pyplot, you can use the xlabel() and ylabel() functions to set a label for the x- and y-axis.

How do you label X and Y axis on a scatter plot?

Then, click on the "Chart Tools" tab that appears at the top of the screen. Next, click on the "Layout" tab. In the "Labels" section, click on "Axes." A drop-down menu will appear. Click on "X-Axis" or "Y-Axis" to label whichever axis you wish to label.

How do I assign x and y labels in Matplotlib?

The xlabel() function in pyplot module of matplotlib library is used to set the label for the x-axis..


1 Answers

That looks like a strange bug with pandas plotting to me! Here's a way around it:

fig, ax = plt.subplots()
df.plot(kind='scatter',x='X', y='Y', c='C', ax=ax)
ax.set_xlabel("X")
plt.show()

This will give you the graph you expect:

enter image description here

like image 117
Kewl Avatar answered Sep 20 '22 04:09

Kewl