ticker.FixedFormatter策略显示ax2轴的抽搐

问题描述 投票:0回答:1

给出3个数组:

X1 = 10.00, 30.10, 50.20, 70.30 ...

X2 = 1.9976433815311, 2.0109630315475, 2.0372702369401, 2.0665284897891 ...

Y = -0.0000008764356, -0.0000149459573, -0.0000326996870, -0.0000513717121 ...

X1X2Y之间存在一对一的对应关系,即

X1的第i个元素具有X2的第i个相关值和Y的第i个值。

以下是Y作为X1(蓝点)函数的图。

  • 我需要X2轴来显示每个X2值的所有相应的X1值。

second answer on this post之后,

我通过qazxsw poi策略部分完成了这个,其中:qazxsw poi数组需要转换为元组,并且这个元组的每个元素都需要是一个字符串。

可以看出,并非所有ticker.FixedFormatter的红色值都显示为X2的每个值,例如对于X2,相应的X1似乎被取代了。

我不太清楚为什么会这样。如果你能帮助我,我将不胜感激。

X1 = 10.0

X2 = 2.00

像这样的东西将是理想的情节(没有必要的红线):

enter image description here

python matplotlib graph
1个回答
1
投票

在你的代码中,import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker import sys X1 = np.array([10.0000000000000, 30.1000000000000, 50.2000000000000, 70.3000000000000, 90.4000000000000, 110.5100000000000, 130.6100000000000, 150.7100000000000, 170.8100000000000, 190.9100000000000, 211.0100000000000, 231.1100000000000, 251.2100000000000, 271.3100000000000, 291.4100000000000, 311.5200000000000, 331.6200000000000 ]) Y = np.array([-0.0000008764356, -0.0000149459573, -0.0000326996870, -0.0000513717121, -0.0000652350399, -0.0000842214902, -0.0001003825474, -0.0001214363281, -0.0001376971422, -0.0001572720132, -0.0001971891337, -0.0002203926200, -0.0002747064193, -0.0003217228112, -0.0003764577474, -0.0004657478828, -0.0006232016207]) X2 = np.array([1.9976433815311, 2.0109630315475, 2.0372702369401, 2.0665284897891, 2.0995743328944, 2.1392386324550, 2.1789200955649, 2.2290243968267, 2.2872281293691, 2.3180577547912, 2.4100643103912, 2.4826981368480, 2.5794602952095, 2.6764219232389, 2.7963983991814, 2.9740753305878, 3.3107035136072]) ##### Plotting: fig, ax1 = plt.subplots() ax1.plot(X1, Y, linestyle='--', marker="o", markersize=6, color='blue') ax1.set_ylabel('Y', fontsize=20) # Make the ax1-ticks and ax1-tick-labels match the line color (blue): ax1.set_xlabel('X1', fontsize=20, color='blue') plt.setp(ax1.get_xticklabels(), rotation='45') # rotate them # Create a new axis: ax2 = ax1.twiny() # Make the ax2-ticks and ax2-tick-labels match the red color: ax2.set_xlabel('X2', fontsize=20, color='red') ax2.tick_params('x', colors='red') fig.tight_layout() ax2.set_xlim(1.9, 3.4) ax1.set_ylim(-0.0007, 1.1e-5) ax2.set_ylim(-0.0007, 1.1e-5) ax1.grid() # Convert all X2 elements to a list of strings: X2_string_all = [] for i in X2: aux = "%.2f" % i X2_string = str(aux) X2_string_all.append(X2_string) # Convert that list into a tuple: X2_string_all_tuple = tuple(X2_string_all) ax1.xaxis.set_major_locator(ticker.FixedLocator((X1))) ax2.xaxis.set_major_formatter(ticker.FixedFormatter((X2_string_all_tuple))) plt.show() 不知道它应该像enter image description here一样,只是使用不同的标签。所以你需要告诉它,

ax2

然后只需对两个轴使用相同的刻度位置,

ax1

并用ax2.set_xlim(ax1.get_xlim()) 的值标记ax1.set_xticks(X1) ax2.set_xticks(X1) 的刻度

ax2

完整代码:

X2

ax2.set_xticklabels(["%.2f" % i for i in X2])

© www.soinside.com 2019 - 2024. All rights reserved.