I was trying to use matplotlib and pandas to create a bar chart that shows the daily change in COVID-19 cases for the USA.
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv('https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv')
display(data.head(10))
df = data.groupby('date').sum()
df['index'] = range(len(df))
df['IsChanged'] = df['cases'].diff()
df.at['2020-01-21', 'IsChanged'] = 0.0
x = df['index']
z = df['IsChanged']
plt.figure(figsize=(20,10))
plt.grid(linestyle='--')
plt.bar(x,z)
plt.show()
The graph that I get though, looks like this:
.
The width of the bars of the chart are not even. I tried setting a specific width, but that didn't work. Is there a way to fix this?
This can be resolved by specifying the resolution. For example, try setting dpi=300. The graph in the answer is an image of the output with the DPI specified in your code.
plt.figure(figsize=(20,10),dpi=300)

While this does not directly answer your question, one might want to consider plt.fill_between() when the barplot has lots of bars. (since if you can not distinguish the bars from each other the barplot kind of loses its purpose)
For example
plt.fill_between(x, 0, z, step='mid', facecolor=(0.3, 0.3, 0.45 ,.4), edgecolor=(0, 0, 0, 1))
plt.grid(ls= ':', color='#6e6e6e', lw=0.5);

or even:
plt.fill_between(x, 0, z, facecolor=(0.3, 0.3, 0.45 ,.4), edgecolor=(0, 0, 0, 1))
plt.grid(ls= ':', color='#6e6e6e', lw=0.5);

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