简体   繁体   中英

Customized x-axis matplotlib

I just want to use a list of decimal years to assign the labels and ticks for a customized x-axis:

labels = [1992.71, 1991.67, 1990.5, 1989.54, 1988.5, 1987.5, .., 1700.5]

IMPORTANT: The interval between 2 consecutive values in the above list is not constant, I only care about steps here, so every position in the list should be a tick or a bin.

The problem is that if I use all the labels in the list, the graph gets too dense. By the way, inside my graph lies a PNG image, not a plot.

So, I have decided (maybe wrongly) to generate a second list with only the values I need (this time using strings):

labels2 = ['1992.71','','','','','1987.50', etc.]

Ideally, I would like the x-axis to have either this configuration:

在正确的 bin 编号中选择标签并且没有刻度

or this one:

右侧 bin 编号中的选定标签和相关刻度,没有其他刻度

or this one:

在 bin 开始时选择的标签和相关的刻度;剩下

So far I have been playing with these functions:

ax.set_xticklabels
plt.locator_params
ax.tick_params
plt.xticks
ax.xaxis.set_ticks
ax.xaxis.set_major_formatter
...

with no success.

This is the closest I have been:

在此处输入图像描述

But the sequence of labels gets CUT in the right hand-side of the x-axis and never reaches the end of the list, so it finishes half-way through the list (which should end in 1700.5):

在此处输入图像描述

Also, I just want to display the ticks corresponding to the selected labels and not all of them.

this is my code:

plt.locator_params(axis='x', nbins=len(labels2)-1)
ax.set_xticklabels(labels2, rotation=90 )
ax.tick_params(axis='x', which='major', length=4, labelsize=2)

In essence, currently I cannot reproduced what I want to,

any ideas?

First set the tick locations using set_xticks and then set the labels using set_xticklabels with an array of the same length. If you don't want to label each tick then set fewer ticks and labels as in the right subplot. Make sure the number of labels always equals the number of ticks set .

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os
import matplotlib
import numpy as np

file = os.path.join(os.path.dirname(matplotlib.__file__), 'mpl-data/sample_data/Minduka_Present_Blue_Pack.png')
img = mpimg.imread(file)
labels = [1992.71, 1991.67, 1990.5, 1989.54, 1988.5, 1987.5, 1980.1, 1700.5]

fig,(ax1,ax2) = plt.subplots(ncols=2)

ax1.imshow(img)
ax1.set_xticks(np.linspace(0, img.shape[1], len(labels)))
ax1.set_xticklabels(labels, rotation = 90)

ax2.imshow(img)
ax2.set_xticks(np.linspace(0, img.shape[1], len(labels))[::2])
ax2.set_xticklabels(labels[::2], rotation = 90)

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM