I have dataframe 'df' with 2 columns Date/Time and Value:
import numpy as np
import pandas as pd
df = pd.DataFrame(pd.date_range('2012-06-01','2012-06-04', freq='H'), columns=['date/time'])
data = np.random.randint(5, 100, 73)
temp= pd.DataFrame(data, columns=['Value'])
df['Value']=temp
df.head()
When I draw a line plot with this data by:
lines=df.plot.line(x='date/time', y='Value')
I get this graph: enter image description here
I am happy with the graph but I want my x-axis to display only the month names. Also in my actual graph, I have a lot of dates with varying months, so when displaying it the x-axis labels should not overlap. Can anyone help me with this, please?
I already looked at stuff like .xaxis.set_major_locator but I can't get it to work.
I had to change your code a little because it used a hourly range over 3 days, which results in all the months being June. Also, your temp
line is unnecessary because you could equivalently create and directly assign the random integers to df['Value']
without first making a temp
dataframe.
import numpy as np
import pandas as pd
df = pd.DataFrame(pd.date_range('2011-06-01','2012-06-04', freq='M'), columns=['date/time'])
df['Value'] = np.random.randint(5, 100, len(df.index))
fig = plt.figure()
ax = fig.add_subplot(111)
months_list = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
### Iterate over the TimeStamp objects, calling the month format of each
months = [months_list[dt.month - 1] for dt in df['date/time']]
ax.plot(months, df['Value'])
plt.show()
For the part about avoiding overlapping tick labels, you could do a basic rotation of the labels:
ax.tick_params(axis='x', labelrotation=30)
or refer to these answers that show two different ways to do this:
Here's the outcome:
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