Matplotlib 自定义刻度和分组网格

huangapple go评论53阅读模式
英文:

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()

Resulting Plot

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()

Resulting Plot

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()

输出:

Matplotlib 自定义刻度和分组网格

英文:

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:

Matplotlib 自定义刻度和分组网格

huangapple
  • 本文由 发表于 2023年7月18日 05:05:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76708073.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定