Python Forum

Full Version: Help with Matplotlib and ordering the axis
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello guys! Im from México and I am analyzing some data from my country.

This is the code that I am working with:

# Importing libraries
import pandas as pd
import matplotlib.pyplot as plt

# Reading .CSV file
df = pd.read_csv("/home/aerospace/Documents/Mortalidad_07.csv")

# Cleaning up the data
df = df.drop(columns=["No especificado", "No especificado.1", "No especificado.2"])
print(df.columns)

# Get the variables that we want
state = df["Estados"][1:33]
man2017 = df["Hombres"][1:33]
wman2017 = df["Mujeres"][0:33]
man2018 = df["Hombres.1"][0:33]
wman2018 = df["Mujeres.1"][0:33]
man2019 = df["Hombres.2"][0:33]
wman2019 = df["Mujeres.2"][0:33]

print(state, man2017)

plt.plot(state, man2017, 'ko')
plt.xticks(rotation=90)
plt.title("Defunciones por homicidio, por entidad federativa 2017")
plt.xlabel("Estados de la República Mexicana")
plt.ylabel("Total de homicidios en 2017")
plt.grid()
plt.show()
The problem is this. If you plot that, we'll see the Y axis ordered randomly, and I want to see the Y axis from lowest to highest. I mean, at the top see the highest values and at the bottom the lowest. the x-axis is arranged alphabetically
Python has functions for sorting data and pandas has a few more.
(Dec-12-2020, 07:41 PM)deanhystad Wrote: [ -> ]Python has functions for sorting data and pandas has a few more.

I tried doing that with "df.sort_values(by="Hombres", ascending=True), but didn't work. How would you do it?
sorted_data = df.sort_values(by="Hombres", ascending=True)

or

df.sort_values(by="Hombres", ascending=True, inplace=True)

It depends on if you only want sorted data for the plot, or if you want the dataframe sorted. If you do not specify inplace=True the sort_values function creates and returns a new dataframe. The original dataframe is not changed.