英文:
Matplotlib custom ticks and grids in groups
问题
我正在尝试以定义的距离批量插入自定义刻度到绘图中。我可以通过手动添加它们来实现,但我正在寻找更好的方法。
示例:
import matplotlib.pyplot as plt
x = [-5, 5]
y = [1, 5]
plt.plot(x, y)
plt.xlim(-10, 10)
plt.grid(axis="x", which='major', color='r', linestyle='--')
plt.yticks([])
# 添加自定义刻度
cticks = [-8, -7, -6, -5, 1, 2, 3, 4]
plt.xticks(cticks)
plt.show()
这是我尝试过的:
import matplotlib.pyplot as plt
import numpy as np
x = [-5, 5]
y = [1, 5]
plt.plot(x, y)
plt.xlim(-10, 10)
plt.grid(axis="x", which='major', color='r', linestyle='--')
plt.xticks(np.arange(1, 5, step=1))
plt.yticks([])
plt.show()
但这只提供了一个批次。
问题: 有没有类似的方法,可以在所需位置的x轴上包含更多批次的刻度标记和网格?
英文:
I am trying to insert custom ticks to a plot in batches with defined distances. I can do this by manually adding them, but I am looking for a better way.
Example:
import matplotlib.pyplot as plt
x = [-5, 5]
y = [1, 5]
plt.plot(x, y)
plt.xlim(-10, 10)
plt.grid(axis="x", which='major', color='r', linestyle='--')
plt.yticks([])
# Adding custom ticks
cticks = [-8, -7, -6, -5, 1, 2, 3, 4]
plt.xticks(cticks)
plt.show()
Here's what I have tried:
import matplotlib.pyplot as plt
import numpy as np
x = [-5, 5]
y = [1, 5]
plt.plot(x, y)
plt.xlim(-10, 10)
plt.grid(axis="x", which='major', color='r', linestyle='--')
plt.xticks(np.arange(1 , 5, step=1))
plt.yticks([])
plt.show()
But this gives only one batch.
Question: Is there a similar way to include more batches of tick marks and grids on the x-axis at desired positions?
答案1
得分: 1
IIUC,您不想手动指定所有刻度,而只想指定批次。您可以在一个循环中执行此操作,该循环将扩展cticks
:
import matplotlib.pyplot as plt
x = [-5, 5]
y = [1, 5]
plt.plot(x, y)
plt.xlim(-10, 10)
plt.grid(axis="x", which="major", color="r", linestyle="--")
plt.yticks([])
# 添加自定义刻度
cticks = []
for n in [-8, 1]: # 在此处指定每个批次的开始
cticks += range(n, n+4)
plt.xticks(cticks)
plt.show()
输出:
英文:
IIUC you don't want to specify all ticks manually but only the batches. You can to this in a loop that will extend cticks
:
import matplotlib.pyplot as plt
x = [-5, 5]
y = [1, 5]
plt.plot(x, y)
plt.xlim(-10, 10)
plt.grid(axis="x", which='major', color='r', linestyle='--')
plt.yticks([])
# Adding custom ticks
cticks = []
for n in [-8, 1]: # specify the beginning of each batch here
cticks += range(n, n+4)
plt.xticks(cticks)
plt.show()
Output:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论