How To Plot A Line Over A Bar Chart
I am trying to plot a line over a bar chart, but when I plotted the line the bar chart disappeared - and so did my x index values. Can anyone help me plot the line and the bar in t
Solution 1:
I have done this using plotly
. I have modified the Deaths
to increase the value so that the line graph is seen.
DataFrame:
DateDeathsCases02020-03-01 51412020-03-02 31322020-03-03 62232020-03-04 92442020-03-05 52652020-03-06 24162020-03-07 102872020-03-08 26382020-03-09 1012292020-03-10 15155102020-03-11 20200112020-03-12 15269122020-03-13 20360132020-03-14 30364142020-03-15 40462152020-03-16 150702162020-03-17 70766172020-03-18 50861182020-03-19 30738192020-03-20 100933
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import pandas as pd
import numpy as np
df = pd.read_csv("a.csv")
fig = make_subplots(1,1)
fig.add_trace(go.Bar(x=df['Date'], y=df['Cases'],
name='Cases',
marker_color = 'yellow',
opacity=0.4,
marker_line_color='rgb(8,48,107)',
marker_line_width=2),
row = 1, col = 1)
fig.add_trace(go.Scatter(x=df['Date'], y=df['Deaths'], line=dict(color='red'), name='Deaths'),
row = 1, col = 1)
fig.show()
Using pandas plotting
import pandas as pd
import matplotlib.pyplotas plt
df = pd.read_csv("a.csv")
fig, ax = plt.subplots(figsize = (15,8))
df.plot(x = 'Date', y = ['Deaths'], kind = 'line', ax = ax)
df.plot(x = 'Date', y= ['Cases'], kind = 'bar', ax = ax, colormap="RdYlBu")
Update: To use Date as index
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("a.csv")
df.set_index("Date", inplace=True)
fig, ax = plt.subplots(figsize = (15,8))
df.plot( y = ['Deaths'], kind = 'line', ax = ax)
df.plot( y= ['Cases'], kind = 'bar', ax = ax, colormap="RdYlBu")
Dataframe with Date
as index. Plotting this will give the same plot as above.
DeathsCasesDate2020-03-01 5142020-03-02 3132020-03-03 6222020-03-04 9242020-03-05 5262020-03-06 2412020-03-07 10282020-03-08 2632020-03-09 101222020-03-10 151552020-03-11 202002020-03-12 152692020-03-13 20360
Post a Comment for "How To Plot A Line Over A Bar Chart"