Pandas plot reverse x axis

Reversing X-Axis in Pandas Plot

In pandas, you can reverse the X-axis of a plot by using the invert_xaxis() method of the matplotlib.pyplot module. Here’s an example:


import pandas as pd
import matplotlib.pyplot as plt

# Create a sample dataframe
data = {'Category': ['A', 'B', 'C', 'D'],
        'Value': [10, 20, 15, 5]}

df = pd.DataFrame(data)

# Plot the dataframe
plt.bar(df['Category'], df['Value'])

# Reverse the X-axis
plt.gca().invert_xaxis()

# Show the plot
plt.show()
  

In the above example, we first import the necessary libraries pandas and matplotlib.pyplot. Then, we create a sample dataframe with two columns: ‘Category’ and ‘Value’.

We plot a bar chart using the bar() function from matplotlib.pyplot, with the ‘Category’ column as the X-axis and the ‘Value’ column as the Y-axis.

Finally, we use the invert_xaxis() method to reverse the X-axis.

To see the plot, we call the show() function from matplotlib.pyplot.

By using plt.gca().invert_xaxis(), the X-axis is reversed, resulting in the ‘D’ category appearing on the left side of the chart, and the ‘A’ category appearing on the right side.

Leave a comment