InlLad
InlLad

Reputation: 69

Force Y axis to start from 0

Is there an easy was for me to force the left y axis to start from 0% instead of 48%?

plot

Here is my code:

fig, ax1 = plt.subplots(figsize=(18,12))
fig.autofmt_xdate()

#update ticks here when graph gets too large
tick_spacing = 5
#y_tick_spacing = 20

ax1.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
color = 'tab:blue'
ax1.set_xlabel('Date',fontsize=18)
ax1.plot(events_df['dt'], events_df['match_rate'], color=color)
ax1.tick_params(axis='y', labelcolor=color)
#ax1.set_ylim([0,100])
ax1.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
#ax1.yaxis.set_major_locator(ticker.MultipleLocator(y_tick_spacing))

ax2 = ax1.twinx()

color = 'tab:red'
ax2.plot(events_df['dt'], events_df['score'], color=color)
ax2.tick_params(axis='y', labelcolor=color)
ax2.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))

fig.tight_layout()
plt.show()

I tried adding ax1.set_ylim([0,100]) but that didn't seem to have an effect and squishes things instead:

plot2

I'm happy with the right y axis starting at 35%.

Here is what I'm hoping for from a google sheets version of the same data:

google_sheets

Upvotes: 1

Views: 1803

Answers (1)

Zephyr
Zephyr

Reputation: 12524

Check this code:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mtick
import numpy as np

events_df = pd.DataFrame({'dt': pd.date_range(start = '2020-02-01', end = '2020-05-16')})
events_df['match_rate'] = 100*(0.48 + (0.9 - 0.48)*np.random.rand(len(events_df.index)))
events_df['score'] = 100*(0.35 + (1 - 0.35)*np.random.rand(len(events_df.index)))

fig, ax1 = plt.subplots(figsize=(18,12))
fig.autofmt_xdate()

tick_spacing = 5

ax1.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
color = 'tab:blue'
ax1.set_xlabel('Date',fontsize=18)
ax1.plot(events_df['dt'], events_df['match_rate'], color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax1.yaxis.set_major_formatter(mtick.PercentFormatter())
ax1.set_ylim([0, 100])

ax2 = ax1.twinx()

color = 'tab:red'
ax2.plot(events_df['dt'], events_df['score'], color=color)
ax2.tick_params(axis='y', labelcolor=color)
ax2.yaxis.set_major_formatter(mtick.PercentFormatter())

fig.tight_layout()
plt.show()

which gives me this plot:

enter image description here

Since I do not have your data, I generate random one in order to make the plot; replace them with yours.
In my case, the 'match_rate' and 'score' columns are float in the ranges (48-90) and (35-100) respectively. So I set

ax1.yaxis.set_major_formatter(mtick.PercentFormatter())

to tell matplotlib that y axis has a percentage format and then I set its limits with

ax1.set_ylim([0, 100])

This depends on the type of data you have in the 'match_rate' and 'score' column: it would be useful to know them.

Upvotes: 1

Related Questions