简体   繁体   中英

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. 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:

# 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).

Here is a sample output: Matplotlib

If you want to get fancy, you can use Plotly, which has hover and zoom features
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_Version

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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