python - Adding secondary X-axis with user-defined list of coordinates -
i have function plotting amount of graphics using pyplot
. code 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() 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 function plots chart. example, if len(results) == len (expers) == 2
, such graph:
i need create secondary x-axis (similarly this, may x-axis , located on top of graph). difference i need set list of coordinates manually (e.g. ax2.set_coords(x_percents)).
i created new axis using ax2 = ax1.twinx()
. then, established coordinates list using ax2.set_xticks(x_percents)
.
but because of each x_percents[i] < x_indices[i]
, got such picture:
(as can see, coordinates of new axis located in left-bottom corner)
how can change function make new x-axis:
located on top side of graph,
has own scale, i.e. each value of
x_percents
corresponds value ofresults[i]
,x_percents
dispersed throughout interval?
your code suggests x_indices
, x_percents
linearly related. keep things clear , useful others, i'll assume following these 2 variables:
x_indices = [0, 5, 10, 25, 50] max_size = max(x_indices) x_percents = [ n/max_size * 100 n in x_indices]
one way achieve creating these dual axes relate same data, have different labels goes this: first create axes, create 1 over (the twinx
/twiny
methods used not strictly necessary, i'll use them here convenience , explaining important issue resulted in setting xticks first axes). ensure limits of both x-axes same, set position of x-ticks same in first axes , change labels:
import matplotlib.pyplot plt vals = [1, 100, 14, 76, 33] # random data, aligned `x_indices` fig, ax1 = plt.subplots(1,1) ax1.plot(x_indices, vals) ax2 = ax1.twiny() # remark: twiny create new axes # y-axis shared ax1, # x-axis independant - important! ax2.set_xlim(ax1.get_xlim()) # ensure independant x-axes span same range ax2.set_xticks(x_indices) # copy on locations of x-ticks first axes ax2.set_xticklabels(x_percents) # give them different meaning
a graph encountered in physics, e.g. wavelength , energy inversely proportionate. on 1 axis, able read off units in 1 scale (e.g. nanometers) whereas other represent same data in different scale (e.g. electron volts).
Comments
Post a Comment