I have a function for plotting amount of graphics using pyplot
. The code is here:
def plot_results(results, expers):
"""
type results: list[list[float]]
type expers: list[int]
"""
label_builder = lambda index: 'experiment ' + str(index + 1)
colors = ('green', 'blue')
x_indices = list(map(compute_filesize, list(range(np.shape(results)[1]))))
x_percents = list(map(compute_percent, list(range(np.shape(results)[1]))))
fig, ax1 = plt.subplots()
for i in range(expers):
ax1.plot(x_indices, results[i], color=colors[i], lw=2, label=label_builder(i))
ax1.legend()
plt.show()
For each value of expers
list my function plots a chart.
For example, if len(results) == len (expers) == 2
, I will get such graph:
I need to create the secondary X-axis (similarly to this, but it may be X-axis and it will be located on the top of graph). Another difference is that I need to set list of coordinates manually (e.g. ax2.set_coords(x_percents)).
I created new axis using ax2 = ax1.twinx()
. Then, I established coordinates list using ax2.set_xticks(x_percents)
.
But because of each x_percents[i] < x_indices[i]
, I got such picture:
(as you can see, all coordinates of new axis are located in left-bottom corner)
How can I change my function to make new X-axis:
located on the top side of the graph,
has its own scale, i.e. each value of x_percents
corresponds to value of results[i]
and
x_percents
dispersed throughout interval?
答案 0 :(得分:2)
您的代码表明x_indices
和x_percents
是线性相关的。为了使事情清楚明白并对其他人有用,我将假设以下两个变量:
x_indices = [0, 5, 10, 25, 50]
max_size = max(x_indices)
x_percents = [ n/max_size * 100 for n in x_indices]
你可以通过一种方法来创建与相同数据相关的双轴,但只是有不同的标签,如下所示:首先创建一个轴,然后创建另一个 over ({{可以使用1}} / twinx
方法但不是绝对必要的,为了方便起见,我将在这里使用它们,并解释导致您为第一个轴设置xticks的重要问题。然后确保两个x轴的极限相同,设置x刻度的位置与第一个轴相同,最后更改标签:
twiny
在物理学中经常遇到这样的图形,例如,波长和能量成反比。在一个轴上,您将能够以一个刻度(例如纳米)读取单位,而另一个轴将以不同的比例(例如电子伏特)表示相同的数据。