Home > Software engineering >  matplotlib, drawing a mean line
matplotlib, drawing a mean line

Time:11-25

new_table = new_table.pivot(index='Date', columns='Country/Region', values='Deaths_Per_Confirmed_Case')
countries = list(new_table.columns)
covid = new_table.reset_index('Date')
covid.set_index(['Date'], inplace=True)
covid.columns = countries

enter image description here

So I create this table above and now I'm trying to plot with it

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

colors = {'Ireland':'#DC3977','US':'#33F7FF'}
plt.style.use('fivethirtyeight')

plot = covid.plot(figsize=(16,12),color=list(colors.values()), linewidth=5, legend=False)
plot.set_ylim([0, covid.max().max()])
plot.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
plot.grid(color='#d4d4d4')
plot.set_xlabel('Date')
plot.set_ylabel('% Mortality Rate')


for country in list(colors.keys()):
    row = covid.iloc[-1]
    plot.text(x = covid.index[-1], y = row[country], color = colors[country], s = country, weight = 'bold')
    plot.text(x = covid.index[-1], y = covid[country].mean(), color = colors[country], s = 'Mean for '   country   ": "   str(round(covid[country].mean(),2)), weight = 'bold')

# Section 9 - Adding Labels
plot.text(x = covid.index[1], y = int(covid.max().max()) 1.5, s = "% Mortality Rate for New Cases", fontsize = 23, weight = 'bold', alpha = .75)
plot.text(x = covid.index[1], y = int(covid.max().max()) 1.3, s = "For Ireland and the US", fontsize = 16, alpha = .75)

And I get an image about what I was looking for: enter image description here

But now I'm trying to figure out how to draw a mean line, so for example, I have mean for Ireland on the right hand side of that image, I have no idea how to draw a line across the graph for this mean value. Really, any help appreciated. Cheers, folks.

CodePudding user response:

Horizontal line: plt.axhline(y_position) #y_position will be your mean_value

Vertical line: plt.axvline(x_position)

For reference, https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.axhline.html

https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.axvline.html

  • Related