Customizing the x or y axis of a matplotlib figure can be easily done with few steps:
Plot a basic figure
Let's start by creating a basic figure using matplotlib, without modifying the axes.
import matplotlib.pyplot as plt
ax = plt.subplot(111)
x = [1,2,3,4,5]
y = [4,1,3,6,1]
plt.scatter(x,y)
plt.grid()
plt.title('How to custom x or y axis in a matplotlib figure ?')
plt.savefig('custom_axes_in_matplotlib_01.png')
plt.show()
Specify minimum and maximum values for the axes using xlim() and ylim()
plt.xlim(0,6)
Specify x and y axes labels
ax.set_xlabel('X AXIS LABEL')
ax.set_ylabel('Y AXIS LABEL')
Changing ticks position
xticks_pos = [i/2.0 for i in range(12)]
plt.xticks(xticks_pos)
Changing ticks labels
xticks_pos = [i/2.0 for i in range(12)]
xticks_labels = [l for l in 'abcdefghijkl' ]
plt.xticks(xticks_pos,xticks_labels)
Changing x-axis ticks color
ax.tick_params(axis='x', colors='red')
Changing x-axis label color
ax.xaxis.label.set_color('red')
Customizing Y-axis
import matplotlib.pyplot as plt
ax = plt.subplot(111)
x = [1,2,3,4,5]
y = [4,1,3,6,1]
plt.scatter(x,y)
plt.xlim(0,6)
plt.ylim(0,6)
ax.set_xlabel('X AXIS LABEL')
ax.set_ylabel('Y AXIS LABEL')
yticks_pos = [i/2.0 for i in range(12)]
plt.yticks(yticks_pos)
plt.grid()
ax.tick_params(axis='y', colors='red')
ax.yaxis.label.set_color('red')
plt.title('How to custom x or y axis in a matplotlib figure ?')
plt.savefig('custom_axes_in_matplotlib_08.png')
plt.show()
References
Links | Site |
---|---|
xlim() | matplotlib.org |
set_xlabel() | matplotlib.org |
xticks() | matplotlib.org |
tick_params() | matplotlib.org |