python - 如何在 ScalarFormatter 之后更改对数图的 xticks 和 yticks?
问题描述
我有这个代码:
# Modules I import
import matplotlib
if os.environ.get('DISPLAY','') == '':
print('no display found. Using non-interactive Agg backend')
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter
from pylab import *
# My Variables to plot
ideal_walltime_list = [135.82, 67.91, 33.955, 16.9775, 8.48875]
cores_plotting = [16, 32, 64, 128, 256]
time_plotting = [135.82, 78.69, 50.62, 46.666, 42.473]
# My plotting part
plt.figure()
plt.scatter(cores_plotting, time_plotting, c='r', label='System wall time')
plt.plot(cores_plotting, ideal_walltime_list, c='k', label='Ideal Wall time')
plt.title('109bEdec_test')
plt.ylabel('Wall time (s)')
plt.xlabel('Cores')
plt.legend(loc='upper right')
plt.yscale('log')
plt.xscale('log')
ax = gca().xaxis
ax.set_major_formatter(ScalarFormatter())
ax.set_minor_formatter(ScalarFormatter())
ay = gca().yaxis
ay.set_major_formatter(ScalarFormatter())
ay.set_minor_formatter(ScalarFormatter())
plt.savefig('109bEdec_test' + '.png',dpi=1800)
plt.show()
当我运行此代码时,我的情节如下所示:
但是,我需要我的 x 轴和 y 轴来显示对应于我的 cores_plotting 变量的刻度,而不是所有格式错误的数字。我试过使用:
plt.xticks(cores_plotting)
plt.yticks(cores_plotting)
但没有成功。
我也试过:
plt.xticks(cores_plotting, ('16', '32', '64', '128', '256'))
plt.yticks(cores_plotting, ['16', '32', '64', '128', '256'])
但也没有成功。现在我只需要将 cores_plotting 项目作为我的 X 和 Y 刻度。
我的 python 版本是 3.6.5,我的 Matplotlib 版本是 3.0.2。
谢谢!
解决方案
您可以先放置将充当主要刻度的自定义刻度,然后隐藏次要刻度。您需要创建一个轴句柄ax
来访问次要刻度。请检查您用于 y-ticklabels 的字符串。
fig, ax = plt.subplots()
plt.scatter(cores_plotting, time_plotting, c='r', label='System wall time')
plt.plot(cores_plotting, ideal_walltime_list, c='k', label='Ideal Wall time')
# Rest of your code here
ax.set_yticks(cores_plotting)
ax.set_yticklabels(['16', '32', '64', '128', '256'])
ax.set_xticks(cores_plotting)
ax.set_xticklabels(['16', '32', '64', '128', '256'])
for xticks in ax.xaxis.get_minor_ticks():
xticks.label1.set_visible(False)
xticks.set_visible(False)
for yticks in ax.yaxis.get_minor_ticks():
yticks.label1.set_visible(False)
yticks.set_visible(False)
Matplotlib 版本问题
matplotlib
似乎以下命令在3+ 版本中不起作用并抛出
TypeError: 'list' object is not callable` 错误。
在这种情况下,使用上述方法分配刻度和刻度标签。
plt.xticks(cores_plotting, ['16', '32', '64', '128', '256']);
plt.yticks(cores_plotting, ['16', '32', '64', '128', '256'])
推荐阅读
- javascript - 有人可以用“Animated.event”向我解释“onScroll”吗?
- java - 具有复合类和数组请求的 Spring Boot 操作
- mysql - 删除关系mysql(laravel)的最佳方法
- ti-basic - 二次公式程序麻烦
- typescript - 如何使类方法用户类型保护在 Typescript 中工作?
- vba - 将对话从共享邮箱移动到共享邮箱中的文件夹中
- sql - 将csv文件导入mysql时是否可以将字符串转换为浮点数?
- python - 在路径中找不到 chromedriver 可执行文件,但我根据 echo 在路径中有它
- asp.net-core - 当模型的 fluentvalidation 在 ASP.Net Core 中无效时,为什么我的控制器会被击中?
- reactjs - 为什么我的 fetch 请求数据不会出现在我的应用程序中?