简体   繁体   English

在numpy / matplotlib.plot中设置轴值

[英]Setting axis values in numpy/matplotlib.plot

I am in the process of learning numpy. 我正在学习numpy。 I wish to plot a graph of Planck's law for different temperatures and so have two np.array s, T and l for temperature and wavelength respectively. 我想绘制普朗克定律在不同温度下的曲线图,因此分别有两个np.array s, Tl分别代表温度和波长。

import scipy.constants as sc
import numpy as np
import matplotlib.pyplot as plt

lhinm = 10000                         # Highest wavelength in nm
T = np.linspace(200, 1000, 10)        # Temperature in K
l = np.linspace(0, lhinm*1E-9, 101)   # Wavelength in m
labels = np.linspace(0, lhinm, 6)     # Axis labels giving l in nm

B = (2*sc.h*sc.c**2/l[:, np.newaxis]**5)/(np.exp((sc.h*sc.c)/(T*l[:, np.newaxis]*sc.Boltzmann))-1)

for ticks in [True, False]:
    plt.plot(B)
    plt.xlabel("Wavelength (nm)")
    if ticks:
        plt.xticks(l, labels)
        plt.title("With xticks()")
        plt.savefig("withticks.png")
    else:
        plt.title("Without xticks()")
        plt.savefig("withoutticks.png")
    plt.show()

I would like to label the x-axis with the wavelength in nm. 我想用nm波长标记x轴。 If I don't call plt.xitcks() the labels on the x-axis would appear to be the index in to the array B (which holds the caculated values). 如果我不调用plt.xitcks() ,则x轴上的标签似乎是数组B的索引(该数组保存了计算值)。

没有滴答声

I've seen answer 7559542 , but when I call plt.xticks() all the values are scrunched up on the left of the axis, rather than being evenly spread along it. 我已经看到了答案7559542 ,但是当我调用plt.xticks()所有值都在轴的左侧向上收缩,而不是沿轴均匀分布。

带有刻度

So what's the best way to define my own set of values (in this case a subset of the values in l ) and place them on the axis? 那么定义我自己的一组值(在本例中为l值的子集)并将其放置在轴上的最佳方法是什么?

The problem is that you're not giving your wavelength values to plt.plot() , so Matplotlib puts the index into the array on the horizontal axis as a default. 问题是您没有将波长值提供给plt.plot() ,因此Matplotlib默认将索引放入水平轴的数组中。 Quick solution: 快速解决方案:

plt.plot(l, B)

Without explicitly setting tick labels, that gives you this: 无需显式设置刻度标签,就可以做到这一点:

在x轴上以适当的值绘制

Of course, the values on the horizontal axis in this plot are actually in meters, not nanometers (despite the labeling), because the values you passed as the first argument to plot() (namely the array l ) are in meters. 当然,此图的水平轴上的值实际上是以米为单位,而不是纳米(尽管有标签),因为作为第一个参数传递给plot() (即数组l )的值是以米为单位。 That's where xticks() comes in. The two-argument version xticks(locations, labels) places the labels at the corresponding locations on the x axis. 这就是xticks()出现的地方。两个参数的xticks(locations, labels)版本将标签放置在x轴上的相应位置。 For example, xticks([1], 'one') would put a label "one" at the location x=1, if that location is in the plot. 例如,如果xticks([1], 'one')在图中x = 1,则会在位置x = 1处放置一个标签“ one”。

However, it doesn't change the range displayed on the axis. 但是,它不会更改轴上显示的范围。 In your original example, your call to xticks() placed a bunch of labels at coordinates like 10 -9 , but it didn't change the axis range, which was still 0 to 100. No wonder all the labels were squished over to the left. 在您的原始示例中,您对xticks()调用在诸如10 -9的坐标处放置了一堆标签,但它并没有更改轴范围,该范围仍然为0到100。难怪所有标签都被挤压到了剩下。

What you need to do is call xticks() with the points at which you want to place the labels, and the desired text of the labels. 您需要做的是调用xticks() ,其中要放置标签的点以及所需的标签文本。 The way you were doing it, xticks(l, labels) , would work except that l has length 101 and labels only has length 6, so it only uses the first 6 elements of l . xticks(l, labels)xticks(l, labels)工作方式可以正常工作,只是l长度为101,而labels长度仅为6,因此它仅使用l的前6个元素。 To fix that, you can do something like 要解决此问题,您可以执行类似的操作

plt.xticks(labels * 1e-9, labels)

where the multiplication by 1e-9 converts from nanometers (what you want displayed) to meters (which are the coordinates Matplotlib actually uses in the plot). 1e-9的倍数从纳米(要显示的内容)转换为米(这是Matplotlib在绘图中实际使用的坐标)。

带有适当标签的固定地块

You can supply the x values to plt.plot , and let matplotlib take care of setting the tick labels. 您可以将x值提供给plt.plot ,让matplotlib负责设置刻度线标签。

In your case, you could plot plt.plot(l, B) , but then you still have the ticks in m, not nm. 在您的情况下,您可以绘制plt.plot(l, B) ,但是然后您仍然在m而不是nm中有刻度。

You could therefore convert your l array to nm before plotting (or during plotting). 因此,您可以在绘图之前(或绘图期间)将l数组转换为nm。 Here's a working example: 这是一个工作示例:

import scipy.constants as sc
import numpy as np
import matplotlib.pyplot as plt

lhinm = 10000                         # Highest wavelength in nm
T = np.linspace(200, 1000, 10)        # Temperature in K
l = np.linspace(0, lhinm*1E-9, 101)   # Wavelength in m
l_nm = l*1e9                          # Wavelength in nm
labels = np.linspace(0, lhinm, 6)     # Axis labels giving l in nm

B = (2*sc.h*sc.c**2/l[:, np.newaxis]**5)/(np.exp((sc.h*sc.c)/(T*l[:, np.newaxis]*sc.Boltzmann))-1)

plt.plot(l_nm, B)
# Alternativly:
# plt.plot(l*1e9, B)
plt.xlabel("Wavelength (nm)")
plt.title("With xticks()")
plt.savefig("withticks.png")
plt.show()

在此处输入图片说明

You need to use same size lists at the xtick . 您需要在xtick处使用相同的大小列表。 Try setting the axis values separately from the plot value as below. 尝试如下设置轴值和绘图值。

import scipy.constants as sc
import numpy as np
import matplotlib.pyplot as plt

lhinm = 10000                         # Highest wavelength in nm
T = np.linspace(200, 1000, 10)        # Temperature in K
l = np.linspace(0, lhinm*1E-9, 101)   # Wavelength in m
ll = np.linspace(0, lhinm*1E-9, 6)    # Axis values
labels = np.linspace(0, lhinm, 6)     # Axis labels giving l in nm

B = (2*sc.h*sc.c**2/l[:, np.newaxis]**5)/(np.exp((sc.h*sc.c)/(T*l[:, np.newaxis]*sc.Boltzmann))-1)

for ticks in [True, False]:
    plt.plot(B)
    plt.xlabel("Wavelength (nm)")
    if ticks:
        plt.xticks(ll, labels)
        plt.title("With xticks()")
        plt.savefig("withticks.png")
    else:
        plt.title("Without xticks()")
        plt.savefig("withoutticks.png")
    plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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