Tom Hughes
Tom Hughes

Reputation: 287

Garbled x-axis labels in matplotlib subplots

I am querying COVID-19 data and building a dataframe of day-over-day changes for one of the data points (positive test results) where each row is a day, each column is a state or territory (there are 56 altogether). I can then generate a chart for every one of the states, but I can't get my x-axis labels (the dates) to behave like I want. There are two problems which I suspect are related. First, there are too many labels -- usually matplotlib tidily reduces the label count for readability, but I think the subplots are confusing it. Second, I would like the labels to read vertically; but this only happens on the last of the plots. (I tried moving the rotation='vertical' inside the for block, to no avail.)

The dates are the same for all the subplots, so -- this part works -- the x-axis labels only need to appear on the bottom row of the subplots. Matplotlib is doing this automatically. But I need fewer of the labels, and for all of them to align vertically. Here is my code:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# get current data
all_states = pd.read_json("https://covidtracking.com/api/v1/states/daily.json")
# convert the YYYYMMDD date to a datetime object
all_states[['gooddate']] = all_states[['date']].applymap(lambda s: pd.to_datetime(str(s), format = '%Y%m%d'))

# 'positive' is the cumulative total of COVID-19 test results that are positive 
all_states_new_positives = all_states.pivot_table(index = 'gooddate', columns = 'state', values = 'positive', aggfunc='sum')
all_states_new_positives_diff = all_states_new_positives.diff()

fig, axes = plt.subplots(14, 4, figsize = (12,8), sharex = True )
plt.tight_layout
for i , ax in enumerate(axes.ravel()):
    # get the numbers for the last 28 days
    x = all_states_new_positives_diff.iloc[-28 :].index
    y = all_states_new_positives_diff.iloc[-28 : , i]
    ax.set_title(y.name, loc='left', fontsize=12, fontweight=0)
    ax.plot(x,y)

plt.xticks(rotation='vertical')
plt.subplots_adjust(left=0.5, bottom=1, right=1, top=4, wspace=2, hspace=2)
plt.show();

Upvotes: 0

Views: 1842

Answers (1)

BigBen
BigBen

Reputation: 50143

Suggestions:

  1. Increase the height of the figure.
    fig, axes = plt.subplots(14, 4, figsize = (12,20), sharex = True)
    
  2. Rotate all the labels:
    fig.autofmt_xdate(rotation=90)
    
  3. Use tight_layout at the end instead of subplots_adjust:
    fig.tight_layout()
    

enter image description here

Upvotes: 1

Related Questions