问题
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