Issue
i used Pandas and supposed we have the following DataFrame :
ax = madagascar_case[["Ratio"]].loc['3/17/20':]
ax.tail()
i would like to show a bar chart following ratio values and add a vertical line related to a specific date for instance : '4/20/20' :
when I try the code below :
ax = madagascar_case[["Ratio"]].loc['3/17/20':].plot.bar(figsize=(17,7), grid = True)
# to add a vertical line
ax.axvline("4/20/20",color="red",linestyle="--",lw=2 ,label="lancement")
the result is the vertical line (red) is at the wrong date and there is no label :
So to fix that I try another code by using matplotlib:
p = '4/20/20'
# Dataframe
ax = madagascar_case[["Ratio"]].loc['3/17/20':]
# plot a histogram based on ax
plt.hist(ax,label='ratio')
# add vertical line
plt.axvline(p,color='g',label="lancement")
plt.legend()
plt.show()
The result was worse than expected. :
is there an easiest way to fix that ?
RVA92 >> I followed your last code :
df = madagascar_case.loc['3/19/20':,'Ratio'].copy()
fig,ax = plt.subplots()
# plot bars
df.plot.bar(figsize=(17,7),grid=True,ax=ax)
ax.axvline(df.index.searchsorted('4/9/20'), color="red", linestyle="--", lw=2, label="lancement")
plt.tight_layout()
the result is it works when I change the date to '4/9/20' for example , but when I change the date to '4/20/20' it doesn't fit correctly I don't know why ?
ax.axvline(df.index.searchsorted('4/20/20'), color="red", linestyle="--", lw=2, label="lancement")
Solution
- You can use the index number for a given date, to plot a vertical line,
df.index.searchsorted('3/20/20')
returns the index number for the given date.
# Import libraries
import pandas as pd
import matplotlib.pyplot as plt
# Create test data
madagascar_case = pd.DataFrame(data={'Ratio': [0.5, 0.7, 0.8, 0.9]}, index=['3/19/20', '3/20/20', '3/21/20', '3/22/20'])
# Choose subset of data
df = madagascar_case.loc['3/19/20':, 'Ratio'].copy()
# Set up figure
fig, ax = plt.subplots()
# Plot bars
df.plot.bar(figsize=(17, 7), grid=True, ax=ax)
# Plot vertical lines
ax.axvline(df.index.searchsorted('3/20/20'), color="red", linestyle="--", lw=2, label="lancement")
ax.axvline(df.index.searchsorted('3/22/20'), color="red", linestyle="--", lw=2, label="lancement")
Answered By - RVA92
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.