I created a chart in matplotlib using python and the x-axis is the days of the week (Mon-Sun). When the data was plotted though, the x-axis is not arranged Mon-Sun.
Is there way I can re-order the x-axis to have it be formatted this way?
or is there a way I can re-order the dataset? It is a csv file that is being read using the panda dataframe
Example Data: (lives in csv: './data/Days_Summary.csv')
Day Value
Monday 56
Tuesday 23
Wednesday 34
Thursday 56
Friday 58
Saturday 70
Sunday 43
Code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.read_csv('./data/Days_Summary.csv')
days_values=df.groupby(['day'])['day'].count().plot(kind='bar')
plt.xlabel('Day')
plt.ylabel('Values')
plt.show()
Use .loc to set the day order:
field = "Day"
day_order = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
ax = df.set_index(field).loc[day_order].plot(kind="bar", legend=False)
ax.set_ylabel("Value")

Note: Using groupby() and count() will not give you the values in the Value field, but will instead count the number of rows in each group. In this case, you'll just get a count of 1 for each day. Hence this answer assumes that
you actually want to plot the values in Value for each day.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With