【问题标题】:Changing tick labels without affecting the plot更改刻度标签而不影响绘图
【发布时间】:2015-08-16 22:21:18
【问题描述】:

我正在使用 matplotlib 在 python 中绘制一个二维数组,但在格式化刻度线时遇到了问题。因此,首先,我的数据目前被组织为具有(海拔,纬度)的二维数组。我正在绘制作为高度和纬度函数的电子密度值(基本上是特定时间的纵向切片)。

我想以 30 度的间隔标记从 -90 到 90 度的 x 轴,并用另一个高程数组标记 y 值(每个模型运行都有不同的高程值,因此我无法手动分配任意高程)。我有一个带有纬度值的数组,另一个带有高程值的数组都是一维数组。

这是我的代码:

from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt

#load the netcdf file into a variable
mar120="C:/Users/WillEvo/Desktop/sec_giptie_cpl_mar_120.nc"

#grab the data into a new variable
fh=Dataset(mar120,mode="r")

#assign model variable contents to python variables
lons=fh.variables['lon'][:]
lats=fh.variables['lat'][:]
var1=fh.variables['UN'][:]

#specifying which time and elevation to map
ionst=var1[0,:,:,21]
ionst=ionst[0:len(ionst)-1]

#close the netCDF file
fh.close()

#Set the figure, size, and resolution
plt.figure(figsize=(8,6), dpi=100, facecolor='white')
plt.subplot(1,1,1)

plt.imshow(ionst, origin='lower', interpolation='spline16')

plt.xticks([-90, -60, -30, 0, 30, 60, 90])  
plt.show()

如果我不包含 plt.xticks 参数,我会得到以下良好的图像但错误的刻度标签:

如果我包含 plt.xticks 参数,我会得到以下信息:

我该如何解决这个问题?我希望数据跟随轴的变化(但要准确)。我还需要对 y 轴执行此操作,但无需手动输入值,而是提供一组值。谢谢

【问题讨论】:

标签: python numpy multidimensional-array matplotlib axes


【解决方案1】:

使用imshowextent 参数设置图像的x 和y 范围,并使用aspect='auto' 允许调整图像的纵横比以适合图形。比如下面的代码

In [68]: from scipy.ndimage.filters import gaussian_filter

In [69]: np.random.seed(12345)

In [70]: a = np.random.randn(27, 36)

In [71]: b = gaussian_filter(a, 4)

In [72]: ymin = 0

In [73]: ymax = 1

In [74]: plt.imshow(b, origin='lower', extent=[-90, 90, ymin, ymax], aspect='auto')
Out[74]: <matplotlib.image.AxesImage at 0x1115f02d0>

In [75]: plt.xticks([-90, -60, -30, 0, 30, 60, 90])
Out[75]: 
([<matplotlib.axis.XTick at 0x108307cd0>,
  <matplotlib.axis.XTick at 0x1101c1c50>,
  <matplotlib.axis.XTick at 0x1115d4610>,
  <matplotlib.axis.XTick at 0x1115f0d90>,
  <matplotlib.axis.XTick at 0x1115ff510>,
  <matplotlib.axis.XTick at 0x11161db10>,
  <matplotlib.axis.XTick at 0x111623090>],
 <a list of 7 Text xticklabel objects>)

生成此图:

【讨论】:

  • 非常感谢! matplotlib 的文档太多了,有时找到你需要的东西是一场噩梦。节省了我数小时的搜索时间。谢谢!
  • 我知道已经有一段时间了,但我正在研究如何抑制 matplotlib 在笔记本中打印 matplotlib.axis.XTick at 0x... 行。有任何想法吗?谢谢。
  • 我将回答我自己的问题,以防万一有人需要这个:要么用分号结束最后一个绘图语句,要么在所有绘图语句之后添加一个plt.show()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
  • 1970-01-01
  • 2012-01-21
  • 1970-01-01
  • 2022-10-15
  • 1970-01-01
相关资源
最近更新 更多