Reputation: 2763
I have been trying to plot data on Matplotlib and I seem to have overlapping YTicks. I am not sure how to adjust them.
Code
import matplotlib.pyplot as plt
data= [4270424, 4257372, 4100352, 4100356, 4100356]
plt.figure(figsize=(10,5))
plt.plot(data, 'ko-')
plt.ylabel('Data point')
plt.xlabel('Iteration point')
plt.yticks(data)
plt.margins(0.05, 0.1)
plt.show()
What I wanted is that the numbers to be there, but is it possible to increase the space between the data points?
Upvotes: 3
Views: 2238
Reputation: 4333
If there are many close datapoints on y-axis, they overlap. You can avoid showing all of them. You can show only one of too close y-ticks. But the rest can be shown on the plot itself (not on y-axis).
Something like that can be used:
import matplotlib.pyplot as plt
data= [4270424, 4257372, 4100352, 4100356, 4100356]
fig, ax = plt.subplots(figsize=(10,8))
#Collect only those ticks that are distant enough from each other
#in order to get rid of ticks overlapping on y-axis:
yticks = [min(data)]
for i in sorted(data[0:]):
if i-yticks[-1] > 3500:
yticks.append(i)
#################################################################
plt.plot(data, 'ko-')
plt.ylabel('Data point', fontsize=12)
plt.xlabel('Iteration point', fontsize=12)
plt.yticks(yticks)
plt.margins(0.05, 0.1)
#Showing y-ticks right on the plot
offset = -1.45
x = ax.get_xticks()
for xp, yp in zip(x, data):
label = "%s" % yp
plt.text(xp-offset, yp+offset, label, fontsize=12, horizontalalignment='right', verticalalignment='bottom')
#################################
ax.grid()
plt.show()
You can also switch off displaying yticks on y-axis completely. In this case change this line plt.yticks(yticks)
to this: plt.yticks(yticks, visible=False)
In this case you don't need ticks collecting part of code at all. But if you keep it, you can turn displaying on later if needed.
Upvotes: 4