gpt4 book ai didi

python - 如何在Python中强制绘图显示x轴值

转载 作者:行者123 更新时间:2023-12-01 02:10:38 25 4
gpt4 key购买 nike

在 python 中设置 x 轴时,我在制作简单绘图时遇到问题。这是我的代码:

import import matplotlib.pyplot as plt

y = [2586.087776040828,2285.8044466570227,1991.0556336526986,1719.7261325405243,1479.8272625661773,1272.5176077500348,1096.4367842436593,949.02201512882527,826.89866676342137,726.37921828890637,636.07392349697909,553.52559247838076,480.71257022562935,418.00424110010181,364.41801903538288,318.67575156686001,280.17668207838426,248.15399589447813,221.75070551820284,199.59983992701842,179.72014852370447,162.27141772637697,147.14507926321306,134.22828323366301,123.36572367962557,114.33589702168332,106.8825327470323,100.69181027167537,95.515144406404971,91.091036326792434]
x = range(0,30)

fig3_4 ,ax3_4 = plt.subplots()
ax3_4.semilogx(range(0,30),(loss_ave_hist))
ax3_4.set_title('Validation Performance')
# ax3_4.set_xticks(np.arange(0,30, 1.0))
ax3_4.set_xlabel('i')
ax3_4.set_ylabel('Average Loss')
fig3_4.show()
plt.show()

我相信我的代码是正确的!注意我注释的代码行,它应该设置具有我想要的值的轴,但是,它会引发错误。我想不通找出原因!

这是我的情节:

enter image description here

最佳答案

这是一种制作 semilogx 图的方法,但 xticks 根据其原始(非对数)值进行标记。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

y = np.array([2586.087776040828, 2285.8044466570227, 1991.0556336526986, 1719.7261325405243, 1479.8272625661773, 1272.5176077500348, 1096.4367842436593, 949.02201512882527, 826.89866676342137, 726.37921828890637, 636.07392349697909, 553.52559247838076, 480.71257022562935, 418.00424110010181, 364.41801903538288, 318.67575156686001, 280.17668207838426, 248.15399589447813, 221.75070551820284, 199.59983992701842, 179.72014852370447, 162.27141772637697, 147.14507926321306, 134.22828323366301, 123.36572367962557, 114.33589702168332, 106.8825327470323, 100.69181027167537, 95.515144406404971, 91.091036326792434])
x = np.arange(1, len(y)+1)

fig, ax = plt.subplots()
ax.plot(x, y, 'o-')
ax.set_xlim(x.min(), x.max())
ax.set_xscale('log')
formatter = mticker.ScalarFormatter()
ax.xaxis.set_major_formatter(formatter)
ax.xaxis.set_major_locator(mticker.FixedLocator(np.arange(0, x.max()+1, 5)))
plt.show()

产量 enter image description hereFixedLocator(np.arange(0, x.max()+1, 5)))x 中的每 5 个值处放置一个刻度线。使用 ax.xaxis.set_major_locator(mticker.FixedLocator(x)) 时,xticklabel 有点过于拥挤。

<小时/>

请注意,我将 x = range(0, 30) 更改为 x = np.arange(1, len(y)+1)x 的长度应与 y 的长度匹配,并且由于我们使用的是对数 x 轴,因此从x=0

另请注意,在原始代码中,第一个 y 值 (2586.08...) 缺失,因为其关联的 x 值 0 超出了图表范围在对数尺度上。

关于python - 如何在Python中强制绘图显示x轴值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48724447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com