【问题标题】:Making a scatter plot in matplotlib with special x2 and y2 axes在 matplotlib 中使用特殊的 x2 和 y2 轴制作散点图
【发布时间】:2017-10-07 18:03:01
【问题描述】:

我是绘图的新手。我在 python 中使用 matplotlib 编写了以下代码来构建散点图:

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()

我希望 x1 和 y1 轴从 0 到 821 开始,并使新的 x2 轴从 1 到 577 到垂直线,并在通过垂直线后,再次从 1 到 243 开始;我需要一个与 x2 完全相同的新 y2 轴。有什么方法可以更改我的代码以获得我最喜欢的情节? 这是运行代码后的图:

我想要的情节如下:

【问题讨论】:

  • 运行代码后,图内有两条垂直和水平线,但我不确定我这里上传的图是否打开。我最喜欢的输出是 x1 和 y1 轴从 0 开始,到 821 结束,并在我的绘图的顶部和右侧添加 x2 和 y2,从 1 开始,正好在该行结束到 577,然后再次从 1 开始,正好在该行之后并以 243 结尾

标签: matplotlib plot axis


【解决方案1】:

您可以使用双轴来生成另一个轴,您可以为其设置不同的刻度和刻度标签。

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()

【讨论】:

  • 这正是我所需要的。非常感谢您提供的代码 :-)
  • 如果我想 X2 轴从 54 开始并在垂直线处结束到 630,然后再次从垂直线处的 10 开始并在轴结束处结束到 253,我该怎么办?
猜你喜欢
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-28
  • 2016-11-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
相关资源
最近更新 更多