I'm having trouble tweaking the graph below.
Here's what the dataframe looks like:
Year Some All Ratio
0 2016 9 157 0.057325
1 2017 13 189 0.068783
2 2018 21 216 0.097222
3 2019 18 190 0.094737
4 2020 28 284 0.098592
Here's what I want to do:
- The orange line should be in front of the bars. I tried using the
zorder
parameter and it didn't help. I also tried switch the order of the axes object, but I couldn't get the line to be assigned to the primary axis. - I want the legend on the left side. You'll notice in the code below that I'm using a somewhat large
figsize
argument. If I use a smaller one, the legend will magically move to the left, but I don't want to use a smaller one. - I want to label the bar graphs on top of each bar with its corresponding value. I tried iterating over each value and individually annotating the bars with
ax.annotate
, but I couldn't center the values automatically. In this minimal example, all the values are three digits long, but in the original data I have numbers that four digits long and I couldn't find a good way to make it centered for all of them. - Finally, I want to get rid of the top and right spines. My code below didn't remove them for some reason.
The code to help people get started follows below.
data = {'Year': {0: '2016', 1: '2017', 2: '2018', 3: '2019', 4: '2020'},
'Some': {0: 9, 1: 13, 2: 21, 3: 18, 4: 28},
'All': {0: 157, 1: 189, 2: 216, 3: 190, 4: 284},
'Ratio': {0: 0.05732484076433121,
1: 0.06878306878306878,
2: 0.09722222222222222,
3: 0.09473684210526316,
4: 0.09859154929577464}}
df = __import__("pandas").DataFrame(data)
ax = df.plot(x="Year", y="Ratio",
kind="line", linestyle='-', marker='o', color="orange",
figsize=((24,12))
)
df.plot(x="Year", y="All",
kind="bar", ax=ax, secondary_y=True
)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)