python - Formatting datetime xlabels in matplotlib

Python - Formatting datetime xlabels in matplotlib

In Matplotlib, you can format datetime x-labels using the mdates.DateFormatter class from the matplotlib.dates module. Here's an example:

import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import datetime import numpy as np # Sample data dates = np.array([ datetime(2022, 1, 1), datetime(2022, 2, 1), datetime(2022, 3, 1), datetime(2022, 4, 1), datetime(2022, 5, 1) ]) values = np.array([10, 20, 15, 30, 25]) # Plotting fig, ax = plt.subplots() ax.plot(dates, values, marker='o') # Formatting x-labels as dates date_formatter = mdates.DateFormatter('%Y-%m-%d') # Adjust the format as needed ax.xaxis.set_major_formatter(date_formatter) # Ensure a nice formatting of the dates fig.autofmt_xdate() plt.xlabel('Date') plt.ylabel('Values') plt.title('Datetime X-labels Formatting Example') plt.show() 

In this example:

  • mdates.DateFormatter('%Y-%m-%d') is used to create a date formatter with the desired format ('%Y-%m-%d' in this case).
  • ax.xaxis.set_major_formatter(date_formatter) sets the x-axis major formatter to the created DateFormatter.
  • fig.autofmt_xdate() ensures a nice formatting of the dates to prevent overlapping.

You can adjust the format string in DateFormatter to match your specific needs. Common format codes include:

  • %Y: Year with century as a decimal number.
  • %m: Month as a zero-padded decimal number.
  • %d: Day of the month as a zero-padded decimal number.
  • %H: Hour (00-23).
  • %M: Minute (00-59).
  • %S: Second (00-59).

Examples

  1. "Matplotlib plot with datetime x-axis"

    • Code Implementation:
      import matplotlib.pyplot as plt import datetime x = [datetime.datetime(2022, 1, 1), datetime.datetime(2022, 1, 2), datetime.datetime(2022, 1, 3)] y = [1, 3, 2] plt.plot(x, y) plt.show() 
      Description: Create a simple Matplotlib plot with datetime values on the x-axis.
  2. "Custom date format for Matplotlib x-axis labels"

    • Code Implementation:
      import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime x = [datetime.datetime(2022, 1, 1), datetime.datetime(2022, 1, 2), datetime.datetime(2022, 1, 3)] y = [1, 3, 2] plt.plot(x, y) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) plt.show() 
      Description: Set a custom date format for Matplotlib x-axis labels.
  3. "Rotate datetime x-axis labels in Matplotlib"

    • Code Implementation:
      import matplotlib.pyplot as plt import datetime x = [datetime.datetime(2022, 1, 1), datetime.datetime(2022, 1, 2), datetime.datetime(2022, 1, 3)] y = [1, 3, 2] plt.plot(x, y) plt.xticks(rotation=45) plt.show() 
      Description: Rotate datetime x-axis labels for better readability in Matplotlib.
  4. "Matplotlib x-axis date range"

    • Code Implementation:
      import matplotlib.pyplot as plt import datetime start_date = datetime.datetime(2022, 1, 1) end_date = datetime.datetime(2022, 1, 10) x = [start_date + datetime.timedelta(days=i) for i in range((end_date - start_date).days + 1)] y = [i for i in range(len(x))] plt.plot(x, y) plt.show() 
      Description: Create a plot with a specified date range on the x-axis in Matplotlib.
  5. "Matplotlib x-axis ticks interval for datetime"

    • Code Implementation:
      import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime x = [datetime.datetime(2022, 1, 1), datetime.datetime(2022, 1, 2), datetime.datetime(2022, 1, 3)] y = [1, 3, 2] plt.plot(x, y) plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=1)) plt.show() 
      Description: Set the interval between datetime x-axis ticks in Matplotlib.
  6. "Matplotlib x-axis datetime range from DataFrame"

    • Code Implementation:
      import matplotlib.pyplot as plt import pandas as pd # Assuming df is a DataFrame with a 'datetime_column' df['datetime_column'] = pd.to_datetime(df['datetime_column']) plt.plot(df['datetime_column'], df['y']) plt.show() 
      Description: Plot datetime values from a DataFrame on the x-axis in Matplotlib.
  7. "Matplotlib x-axis minor ticks for datetime"

    • Code Implementation:
      import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime x = [datetime.datetime(2022, 1, 1), datetime.datetime(2022, 1, 2), datetime.datetime(2022, 1, 3)] y = [1, 3, 2] plt.plot(x, y) plt.gca().xaxis.set_minor_locator(mdates.DayLocator()) plt.show() 
      Description: Add minor ticks to the datetime x-axis in Matplotlib.
  8. "Matplotlib x-axis date range with logarithmic scale"

    • Code Implementation:
      import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime x = [datetime.datetime(2022, 1, 1), datetime.datetime(2022, 1, 2), datetime.datetime(2022, 1, 3)] y = [1, 10, 100] plt.plot(x, y) plt.xscale('log') plt.show() 
      Description: Plot a datetime x-axis with a logarithmic scale in Matplotlib.
  9. "Matplotlib x-axis datetime ticks at specific points"

    • Code Implementation:
      import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime x = [datetime.datetime(2022, 1, 1), datetime.datetime(2022, 1, 2), datetime.datetime(2022, 1, 3)] y = [1, 3, 2] plt.plot(x, y) plt.xticks([datetime.datetime(2022, 1, 1), datetime.datetime(2022, 1, 3)]) plt.show() 
      Description: Set specific datetime points for x-axis ticks in Matplotlib.
  10. "Matplotlib x-axis datetime labels as month names"

    • Code Implementation:
      import matplotlib.pyplot as plt import matplotlib.dates as mdates import datetime x = [datetime.datetime(2022, 1, 1), datetime.datetime(2022, 2, 1), datetime.datetime(2022, 3, 1)] y = [1, 3, 2] plt.plot(x, y) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%b')) plt.show() 
      Description: Display month names as datetime x-axis labels in Matplotlib.

More Tags

excel-2011 supervised-learning visual-studio-2005 abcpdf supertest laravel-middleware react-native sha apache-commons-config scrollbar

More Programming Questions

More Statistics Calculators

More Electrochemistry Calculators

More Everyday Utility Calculators

More Chemical thermodynamics Calculators