简体   繁体   English

如何在 matplotlib 子图中删除除“0”之外的所有 y 轴刻度标签和标记?

[英]How to remove all y-axis tick labels and markers except for '0' in a matplotlib subplot?

The code:编码:

import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

fig, axs = plt.subplots(2, sharex = True, figsize=(9,6),dpi=500, 
                    gridspec_kw={'height_ratios': [3, 1]})    

axs[0].set_title("Smoothed Kalman Point Estimate Fit to " + symbol)
axs[0].plot(dates, price_series, c='black', linestyle = '-', linewidth = 2)
axs[0].plot(dates, kf_point_est, c='yellow', linestyle = '-', linewidth = 1)
axs[0].xaxis.set_major_formatter(DateFormatter("%y"))
axs[0].margins(x=0)

axs[1].set_title("Slope")
axs[1].plot(dates, pos_slope, color='g')
axs[1].plot(dates, neg_slope, color='r')
axs[1].axhline(0, c='black', linestyle = '--', linewidth = 1)
axs[1].xaxis.set_major_formatter(DateFormatter("'%y"))
axs[1].margins(x=0)

Which produces the following plot:这会产生以下情节:

在此处输入图像描述

But I want to remove all y-axis tick labels (and tick markers) apart from if tick label = 0, so that it looks like this:但我想删除除如果刻度标签 = 0 之外的所有 y 轴刻度标签(和刻度标记),使其看起来像这样:

在此处输入图像描述

I understand I only have one other y-axis tick, but I need the code to be robust to handle any amount of tick markers/labels.我知道我只有另一个 y 轴刻度,但我需要代码能够处理任何数量的刻度标记/标签。

Also, I would like to round the remaining 0 to have no decimal places.另外,我想将剩余的 0 舍入为没有小数位。 so it reads "0" as opposed to "0.0000".所以它读为“0”而不是“0.0000”。

If I understand correctly you could do this in one line like如果我理解正确,您可以在一行中执行此操作,例如

axs[1].yaxis.set_ticks([0])

It should be formatted as 0, because I am passing an integer.它应该被格式化为 0,因为我传递的是一个整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM