Search code examples
pythonpython-3.xdatetimematplotlibhighlight

Highlight specific date in x-axis using matplotlib


I have a list of dates which i want to plot on x axis :

x = ['20200116', '20200121', '20200325']

I used below code for plotting:

import matplotlib.pyplot as plt
import datetime
import matplotlib.dates as mdates

x = [datetime.datetime.strptime(date, '%Y%m%d').date() for date in x] ##convert string to dates

plt.fill_between(x, y1, 0, color='gray')
plt.margins(0)
plt.grid(alpha= 0.5)

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%y')) ##changes date format
plt.xlim(xmin=min(x), xmax=max(x))
plt.gcf().autofmt_xdate()

This gives me below chart :

enter image description here

My questions are :

  1. How to show only original dates x = ['20200116', '20200121', '20200325'] in x lables?Then I will not need them to highlight.

  2. If above is not possible then, How to show original dates x = ['20200116', '20200121', '20200325'] with other x lables and also highlight these 3 dates?


Solution

  • Just add plt.xticks(x) at the end.