Making a scatter plot in matplotlib with special x2 and y2 axes

偶尔善良 提交于 2019-12-08 12:18:34

问题


I am a newbie in drawing plots. I have written the following code with matplotlib in python to build a scatterplot:

import numpy as np
import matplotlib.pyplot as plt
Edge_matrix=[[269, 270], [270, 269], [274, 275], [275, 274], [341, 342], 
[342, 341], [711, 712], [712, 711]]
x=[]; y=[]
for i in Edge_matrix:
    x.append(i[0])
    y.append(i[1])
#print(x,y)

plt.scatter(x,y, s=1, c='blue', alpha=1)
plt.axhline(576, linewidth=0.3, color='blue', label='zorder=2', zorder=2)
plt.axvline(576, linewidth=0.3, color='blue', label='zorder=2', zorder=2)
plt.show()

I want the x1 and y1 axes start from 0 to 821 and make new x2 axis starting from 1 to 577 to the vertical line and after passing vertical line, again starting from 1 to 243; I need a new y2 axis exactly like x2. Is there any way to change my code for getting my favorite plot? This is the plot after running the code:

The plot I would like to have is the following:


回答1:


You may use twin axes to produce another axes for which you may set different ticks and ticklabels.

import numpy as np
import matplotlib.pyplot as plt

Edge_matrix=[[269, 270], [270, 269], [274, 275], [275, 274], [341, 342], 
[342, 341], [711, 712], [712, 711]]
x,y = zip(*Edge_matrix)

limits = [0,821]
sec_lim = 243
bp = 576

ax = plt.gca()
ax.set_xlim(limits)
ax.set_ylim(limits)
ax.scatter(x,y, s=1, c='blue', alpha=1)
ax.axhline(bp, linewidth=0.3, color='blue', label='zorder=2', zorder=2)
ax.axvline(bp, linewidth=0.3, color='blue', label='zorder=2', zorder=2)

ax2 = ax.twinx()
ax2.yaxis.tick_right()
ax2.set_ylim(ax.get_ylim())
yticks = ax.get_yticks()
ax2.set_yticks(np.append(yticks[yticks<bp], [bp,bp+sec_lim]) )
ax2.set_yticklabels(np.append(yticks[yticks<bp], [0,sec_lim]).astype(int) )

ax3 = ax.twiny()
ax3.xaxis.tick_top()
ax3.set_xlim(ax.get_xlim())
xticks = ax.get_xticks()
ax3.set_xticks(np.append(xticks[xticks<bp], [bp,bp+sec_lim]) )
ax3.set_xticklabels(np.append(xticks[xticks<bp], [0,sec_lim]).astype(int) )

plt.show()



来源:https://stackoverflow.com/questions/46623411/making-a-scatter-plot-in-matplotlib-with-special-x2-and-y2-axes

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