Joanne
Joanne

Reputation: 503

Setting value for x-axis and y-axis

I have a code like this, and it will present a figure with the x-axis from 1 to 200, and the y-axis also from 1 to 200. But I would like to make the two axes both from -1.5 to 1.5 with 0.5 space.

enter image description here

I have already tried "plt.xticks" and "set_xlim", but I still cannot make it.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy.stats import multivariate_normal

fig, main_ax = plt.subplots(figsize=(5, 5))
divider = make_axes_locatable(main_ax)
top_ax = divider.append_axes("top", 1.05, pad=0.1,sharex=main_ax)

top_ax.xaxis.set_tick_params(labelbottom=False)

main_ax.set_xlabel('dim 1')
main_ax.set_ylabel('dim 2')
top_ax.set_ylabel('Z profile')

x, y = np.mgrid[-1:1:.01, -1:1:.01]
pos = np.empty(x.shape + (2,))
pos[:, :, 0] = x; pos[:, :, 1] = y
rv = multivariate_normal([-0.2, 0.2], [[1, 1.5], [0.25, 0.25]])
z = rv.pdf(pos)
z_max = z.max()

plt.set_cmap(plt.cm.gist_earth)

cur_x = 100
cur_y = 100

main_ax.imshow(z, origin='lower')
main_ax.autoscale(enable=False)
top_ax.autoscale(enable=False)
top_ax.set_ylim(top=z_max)
v_line = main_ax.axvline(cur_x, color='r')
h_line = main_ax.axhline(cur_y, color='y')
v_prof, = top_ax.plot(np.arange(x.shape[1])[::-1], z[:,int(cur_x)], 'r-')
h_prof, = top_ax.plot(np.arange(x.shape[0]), z[int(cur_y),:], 'y-')



plt.show()

Upvotes: 1

Views: 108

Answers (1)

Eiji
Eiji

Reputation: 165

You can simply use this code.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy.stats import multivariate_normal

fig, main_ax = plt.subplots(figsize=(5, 5))
divider = make_axes_locatable(main_ax)
top_ax = divider.append_axes("top", 1.05, pad=0.1,sharex=main_ax)

top_ax.xaxis.set_tick_params(labelbottom=False)

main_ax.set_xlabel('dim 1')
main_ax.set_ylabel('dim 2')
top_ax.set_ylabel('Z profile')

x, y = np.mgrid[-1:1:.01, -1:1:.01]
pos = np.empty(x.shape + (2,))
pos[:, :, 0] = x; pos[:, :, 1] = y
rv = multivariate_normal([-0.2, 0.2], [[1, 1.5], [0.25, 0.25]])
z = rv.pdf(pos)
z_max = z.max()

plt.set_cmap(plt.cm.gist_earth)

# For y axis
main_ax.set_yticks(np.linspace(0,200,7))
main_ax.set_yticklabels(np.linspace(-1.5,1.5,7))

# For x axis
plt.xticks(np.linspace(0,200,7),np.linspace(-1.5,1.5,7))

cur_x = 100
cur_y = 100

main_ax.imshow(z, origin='lower')
main_ax.autoscale(enable=False)
top_ax.autoscale(enable=False)
top_ax.set_ylim(top=z_max)
v_line = main_ax.axvline(cur_x, color='r')
h_line = main_ax.axhline(cur_y, color='y')
v_prof, = top_ax.plot(np.arange(x.shape[1])[::-1], z[:,int(cur_x)], 'r-')
h_prof, = top_ax.plot(np.arange(x.shape[0]), z[int(cur_y),:], 'y-')

enter image description here

Upvotes: 1

Related Questions