Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bars in matplotlib bar chart are not the same width?

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?

like image 805
Dhruv Jain Avatar asked Sep 12 '26 08:09

Dhruv Jain


2 Answers

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)

enter image description here

like image 80
r-beginners Avatar answered Sep 14 '26 22:09

r-beginners


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);

enter image description here

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);

enter image description here

like image 29
np8 Avatar answered Sep 14 '26 20:09

np8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!