简体   繁体   English

将 matplotlib 条形图拆分为 3

[英]Splitting matplotlib bar graph into 3

Plotting the severity of accident by the month which it occurred.按事故发生的月份绘制事故的严重程度。 My data has 3 values for severity (0,1,2) all which are under one graph.我的数据有 3 个严重性 (0,1,2) 值,所有这些值都在一张图下。 I want to create three separate graphs for each severity value.我想为每个严重性值创建三个单独的图表。

month = df.groupby(['Month','Severity']).size().unstack()
print(month)
month.plot(kind='bar')
plt.legend(title = 'Severity')
plt.show()

当前代码

Here's my solution using Matplotlib:这是我使用 Matplotlib 的解决方案:

# Import packages
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

# Create random data - Just convert your data to a Pandas dataframe
months = np.array(['January', 'February', 'March', 'April', 'May', 'June', 'July',
                      'August', 'September', 'October', 'November', 'December'])
numMonths = months.shape[0]

sev0 = np.random.randint(13000, 15500, (numMonths,))
sev1 = np.random.randint(250, 350, (numMonths,))
sev2 = np.random.randint(20, 35, (numMonths,))

d = {'Month': months, 'Sev_0': sev0, 'Sev_1': sev1, 'Sev_2': sev2}
df = pd.DataFrame(data=d)

# Create plots
for i in range(3):
    yData = "Sev_" + str(i)
    plt.figure(figsize=(12,10))
    
    plt.title(yData)
    plt.bar(df.Month, df[yData].to_numpy())
    plt.xlabel('Month')
    plt.ylabel('Number of Accidents')

where df is your data (replace my random data generation with your actual data).其中df是您的数据(用您的实际数据替换我的随机数据生成)。

Here is a sample output:这是一个示例输出: Matplotlib

If you want to get fancy, you can use Plotly, which has hover and zoom features如果你想花哨,你可以使用 Plotly,它具有悬停和缩放功能
Also, you can control which severity value is being plotted when all in one interactive graph.此外,您可以控制在一个交互式图形中绘制的严重性值。

import plotly
import plotly.graph_objs as go
from plotly.offline import init_notebook_mode, plot, iplot, download_plotlyjs
init_notebook_mode(connected=True)
plotly.offline.init_notebook_mode(connected=True)

dataAllSev = []
for i in range(3):
    yData = "Sev_" + str(i)
    
    dataAllSev.append(go.Bar(x=df.Month, y=df[yData].to_numpy(), name=yData))

fig = go.Figure(data=dataAllSev)
fig.update_layout(title="Number of Accidents by Severity Level", xaxis_title='Month', yaxis_title='Number of Accidents')
fig.show()

Here is the combined graph in Plotly:这是 Plotly 中的组合图: Plotly_Version

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

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