Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Matplotlib re-ordering y axis

Attempting to make a simple 2D matplotlib plot, but it’s re-ordering the y-axis labels to keep the graph linear. How can I avoid this?

Code:

data = np.array([
    ['Jun 1', 1.2, 0.2],
    ['Jun 2', 1.3, 1.2],
    ['Jun 3', 1.4, 0.9],
    ['Jun 4', 1.1, 0.5],
    ['Jun 5', 1.6, 1.2],
    ['Jun 6', 2.2, 0.2],
    ['Jun 7', 3.4, 1.6]
])
df = pd.DataFrame(data, columns=['date', 'income', 'spent'])
plt.plot(df['income'])

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’d just like a normal graph:
X axis: index
Y axis: df.income (where the visual plot range is auto-calculated)

The same issue with the scatterplot:

enter image description here

>Solution :

It’s because of your types. When numpy sees a string, it assumes everything in the array to be an object. So your income and spent data is actually text if you dig into the dtypes. Reconvert them before plotting:

data = np.array([
    ['Jun 1', 1.2, 0.2],
    ['Jun 2', 1.3, 1.2],
    ['Jun 3', 1.4, 0.9],
    ['Jun 4', 1.1, 0.5],
    ['Jun 5', 1.6, 1.2],
    ['Jun 6', 2.2, 0.2],
    ['Jun 7', 3.4, 1.6]
])

df = pd.DataFrame(data, columns=['date', 'income', 'spent'])

for c in ['income', 'spent']:
    df[c] = df[c].astype(float)

plt.plot(df['income'])

or (better practice):

data = [
    ['Jun 1', 1.2, 0.2],
    ['Jun 2', 1.3, 1.2],
    ['Jun 3', 1.4, 0.9],
    ['Jun 4', 1.1, 0.5],
    ['Jun 5', 1.6, 1.2],
    ['Jun 6', 2.2, 0.2],
    ['Jun 7', 3.4, 1.6]
]

df = pd.DataFrame(data, columns=['date', 'income', 'spent'])

plt.plot(df['income'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading