Setting Y-Axis Limit in Matplotlib

How can i set the y axis limit in matplotlib

try use matplotlib.pyplot.ylim(low, high) refer this link https://www.geeksforgeeks.org/matplotlib-pyplot-ylim-in-python/

How to set maximum y axis limit in matplotlib

You could do:

ax.set_ylim(lower_limit,upper_limit)

Setting Y limit of matplotlib range automatically

The fastest way to achieve what you want is to subset your DataFrame:

# I've renamed these as they override the builtin min/max
min_ = 20_000
max_ = 42_460

# `mask` is an array of True/False that allows
# us to select a subset of the DataFrame
mask = data["data"].between(min_, max_, inclusive=True)
plot_data = data[mask]

If you set cut=0 on the sns.kdeplot you shouldn't need to set the xlim for the axes, but this may truncate some lines. I've left it out because I think it looks better without it.

Also, as you use sharex on your subplots, I think you only need to call set_xlim once.

Then use plot_data to plot your charts:

ages = {"25-34": "blue", "35-44": "orange", "45-54": "green", "55-64": "red"}
markers = [
plt.Line2D([0, 0], [0, 0], color=color, marker="o", linestyle="")
for color in ages.values()
]

fig = plt.figure(figsize=(10, 11))
fig.suptitle("Title", fontsize=12)
fig.legend(markers, ages.keys(), loc="center right")
gs = fig.add_gridspec(3, hspace=0, height_ratios=[5, 1, 5])
axs = gs.subplots(sharex=True, sharey=False)

sns.histplot(data=plot_data, x="data", bins=200, ax=axs[0])

sns.kdeplot(
data=plot_data,
x="data",
hue="labels",
common_norm=False,
bw_adjust=0.25,
ax=axs[2],
legend=False,
palette=ages.values(),
hue_order=ages.keys(),
# cut=0,
)

axs[0].set_axisbelow(True)
axs[0].set_xlim(min_, max_)
axs[0].grid(b=True, which="minor", color="#eeeeee90", lw=0.5)
axs[0].grid(b=True, which="major", color="#cccccc20", lw=0.8)

# omit ax[1]

axs[2].set_axisbelow(True)
axs[2].set_xlim(min_, max_)
axs[2].grid(b=True, which="minor", color="#eeeeee90", lw=0.5)
axs[2].grid(b=True, which="major", color="#cccccc20", lw=0.8)

Which outputs:

Sample Image

Matplotlib y-axis range

The problem is that you are plotting strings as the content of kss_conc.
You should convert to floats like:

kss_conc = ['12.3', '12.6', '13.0', '12.2', '11.2', '9.9', '10.5']
kss_conc = list(map(float, kss_conc))

Before plotting. Then, you can use plt.ylim([9.9, 13.0]) and it should work.



Related Topics



Leave a reply



Submit