如何在 matplotlib 中增加条形之间的 space 并增加条形宽度

how to increase space between bar and increase bar width in matplotlib

我正在直接从维基百科网站抓取维基百科 table 并绘制 table。我想增加条形宽度,在条形之间添加 space 并使所有条形可见。请问我该怎么办?我的代码如下

#########scrapping#########
html= requests.get("https://en.wikipedia.org/wiki/COVID-19_pandemic_in_Nigeria")
bsObj= BeautifulSoup(html.content, 'html.parser')
states= []
cases=[]

for items in bsObj.find("table",{"class":"wikitable sortable"}).find_all('tr')[1:37]:
    data = items.find_all(['th',{"align":"left"},'td'])

    states.append(data[0].a.text)
    cases.append(data[1].b.text)
  
 ########Dataframe#########
table= ["STATES","CASES"]
tab= pd.DataFrame(list(zip(states,cases)),columns=table)
tab["CASES"]=tab["CASES"].replace('\n','', regex=True)
tab["CASES"]=tab["CASES"].replace(',','', regex=True)
tab['CASES'] = pd.to_numeric(tab['CASES'], errors='coerce')
tab["CASES"]=tab["CASES"].fillna(0)
tab["CASES"] = tab["CASES"].values.astype(int)

#######matplotlib########
x=tab["STATES"]
y=tab["CASES"]
plt.cla()
plt.locator_params(axis='y', nbins=len(y)/4)
plt.bar(x,y, color="blue")
plt.xticks(fontsize= 8,rotation='vertical')
plt.yticks(fontsize= 8)
plt.show()

使用pandas.read_html and barh

  • .read_html 将从网站读取所有表格标签和 return 数据帧列表。
  • barh 将制作水平条而不是垂直条,如果有很多条,这很有用。
  • 如果需要,请延长情节。在这种情况下,(16.0, 10.0),增加10
  • 我建议对 x 使用对数刻度,因为 LagosKogi
  • 相比有很多情况
  • 这并没有在条形之间放置更多 space,但是格式化的图由于增加了尺寸和水平条而更加清晰。
  • .iloc[:36, :5] 从数据框中删除了一些不需要的列和行。
import pandas as pd
import matplotlib.pyplot as plt

# url
url = 'https://en.wikipedia.org/wiki/COVID-19_pandemic_in_Nigeria'

# create dataframe list
dataframe_list = pd.read_html(url)  # this is a list of all the tables at the url as dataframes

# get the dataframe from the list
df = dataframe_list[2].iloc[:36, :5]  # you want the dataframe at index 2

# replace '-' with 0
df.replace('–', 0, inplace=True)

# set to int
for col in df.columns[1:]:
    df[col] = df[col].astype('int')

# plot a horizontal bar
plt.rcParams['figure.figsize'] = (16.0, 10.0)
plt.style.use('ggplot')

p = plt.barh(width='Cases', y='State', data=df, color='purple')
plt.xscale('log')
plt.xlabel('Number of Cases')
plt.show()

绘制df

中的所有数据
df.set_index('State', inplace=True)

plt.figure(figsize=(14, 14))
df.plot.barh()
plt.xscale('log')
plt.show()

4 个子图

  • State 作为索引
plt.figure(figsize=(14, 14))
for i, col in enumerate(df.columns, 1):
    plt.subplot(2, 2, i)
    df[col].plot.barh(label=col, color='green')
    plt.xscale('log')
    plt.legend()
plt.tight_layout()
plt.show()