简体   繁体   English

matplotlib 条形图中的条形宽度不一样?

[英]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.我试图使用 matplotlib 和 pandas 创建一个条形图,显示美国 COVID-19 病例的每日变化。

  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 .例如,尝试设置dpi=300 The graph in the answer is an image of the output with the DPI specified in your code.答案中的图表是 output 的图像,并在您的代码中指定了 DPI。

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.虽然这不能直接回答您的问题,但当条形图有很多条时,可能需要考虑plt.fill_between() (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);

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM