Home > database >  Same x values confuses Matplotlib so y-values are associated with incorrect x-values
Same x values confuses Matplotlib so y-values are associated with incorrect x-values

Time:10-09

This is a simplified version of a much larger dataframe.

import pandas as pd
import matplotlib.pyplot as plt

dfa = pd.DataFrame(
    {
        "Col1": ["A", "A", "H"],
        "Col2": [1, 3, 5],
        "Col3": [2, 4, 6],
    }
)

x = dfa["Col1"]
y = dfa[["Col2", "Col3"]]
fig, ax = plt.subplots()
ax.plot(x,y)
ax.set_xticks(range(len(x)))
ax.set_xticklabels(x)
plt.show()

enter image description here

But if the x-axis labels are unique there is no problem.

dfa = pd.DataFrame(
    {
        "Col1": ["A", "B", "H"],
        "Col2": [1, 3, 5],
        "Col3": [2, 4, 6],
    }
)

enter image description here

Must be a setting/setup somewhere to stop this?

Note: I am using Matplotlib set_xticks/set_xticklabels as the built-in Pandas plot() does not show all the x labels due to many being identical. I need to see every x label.

CodePudding user response:

Instead of plotting against Col1, you might just want to plot against the index and then label them with Col1:

enter image description here

  • Related