In a scenario where you have a series with a datetime index that you wish to visualize, you may encounter a situation where the graph displays timestamps including hours, minutes, and seconds despite your preference for a simpler format like "yyyy-mm" or "2016 March."
To address this issue and achieve the desired formatting, we can leverage the functionalities provided by matplotlib. In particular, the datetime axis can be customized using formatters. These formatters allow you to specify how the tick labels on the x-axis should be displayed.
Here's an example that demonstrates the use of formatters:
<code class="python">import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates # Sample data with hourly timestamps N = 30 drange = pd.date_range("2014-01", periods=N, freq="H") np.random.seed(365) values = {'values':np.random.randint(1,20,size=N)} df = pd.DataFrame(values, index=drange) # Create a plot with incorrect formatting fig, ax = plt.subplots() ax.plot(df.index, df.values) ax.set_xticks(df.index) # Use formatters to achieve the desired formatting ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m")) ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m")) plt.xticks(rotation=90) # Display the updated plot with the desired formatting plt.show()</code>
In this example, we first create a sample DataFrame with hourly timestamps. We then use the DateFormatter from matplotlib.dates to specify that the tick labels on the x-axis should be in the format "%Y-%m", which represents the year and month only. Finally, we call xticks to rotate the tick labels for better readability.
By implementing this approach, you can effectively customize the format of your datetime axis, ensuring that it aligns with your desired display requirements.
The above is the detailed content of How can I format a datetime axis in matplotlib to show only year and month?. For more information, please follow other related articles on the PHP Chinese website!