Pyplot - shift position of y-axis ticks and its data

﹥>﹥吖頭↗ 提交于 2019-12-13 04:19:37

问题


Using pyplot, how do I modify my plot to change the vertical position of my yticks? E.g. in my plot above, I want to move 'Promoter' down and 'CDS' up (along with their 'lines' in the plot).

For the above plot, my x-data is a range of numbers, while my y-data is categorical. Code to reproduce plot as follows:

import matplotlib.pyplot as plt

x_CDS = list(range(661, 668))
y_CDS = ["CDS"] * len(x_CDS)

x_RBS = list(range(649, 656))
y_RBS = ["RBS"] * len(x_RBS)

x_prom = list(range(570, 601))
y_prom = ["Promoter"] * len(x_prom)

plt.figure(figsize=(10,6))
plt.xlim(1, 3002)
plt.xlabel('Nucleotide position')

plt.plot(x_CDS, y_CDS, label='CDS')
plt.plot(x_RBS, y_RBS, label='RBS')
plt.plot(x_prom, y_prom, label='Promoter')

Note: the lines in this case are quite small, but the ranges can be made larger for convenience.

Thanks in advance!


回答1:


By default matplotlib produces some 5% margins on each side of the data. Here it seems you want to increase this margin for the vertical direction. Maybe you want 40%, i.e. plt.margins(y=0.4)?

import matplotlib.pyplot as plt

x_CDS = list(range(661, 668))
y_CDS = ["CDS"] * len(x_CDS)

x_RBS = list(range(649, 656))
y_RBS = ["RBS"] * len(x_RBS)

x_prom = list(range(570, 601))
y_prom = ["Promoter"] * len(x_prom)

plt.figure(figsize=(10,6))

plt.xlabel('Nucleotide position')

plt.plot(x_CDS, y_CDS, label='CDS')
plt.plot(x_RBS, y_RBS, label='RBS')
plt.plot(x_prom, y_prom, label='Promoter')

plt.margins(y=0.4)

plt.show()

The advantage of using margins here instead of changing the ylim is that you do not need to count the categories to find out what useful value to choose for the limits. But of course you may equally change the limits via plt.ylim(-0.8,2.8) toc achieve the same plot.




回答2:


plt.margins(y=10) should provide a padding on the top and bottom of the y-axis ticks. I am using y=10 as an example, please tweak it as necessary. Hope, this is what you were looking for.



来源:https://stackoverflow.com/questions/52172227/pyplot-shift-position-of-y-axis-ticks-and-its-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!