Manim坐标轴位置

0 投票
1 回答
42 浏览
提问于 2025-04-14 16:13

可以移动坐标轴的位置吗?我想绘制更多的科学数据,比如电压随时间的变化。如果有些电压值是负数,它们会穿过x轴,这样图表看起来就不好,因为我还想给x轴和y轴加上标签。

看看下面的代码:

from manim import *

class LineGraphExample(Scene):
    def construct(self):
        plane = NumberPlane(
            x_range = (0, 7),
            y_range = (-2, 5),
            x_length = 7,
            y_length = 5,
            axis_config={"include_numbers": True},
        )
        plane.center()
        y_label = plane.get_y_axis_label("\\text{Voltage [V]}", edge=LEFT, direction=LEFT, buff=0.4)
        x_label = plane.get_x_axis_label("\\text{Time [$\mu$s]}", edge=DOWN, direction=DOWN, buff=0.4)
        self.add(y_label)
        self.add(x_label)
        line_graph = plane.plot_line_graph(
            x_values = [0, 1.5, 2, 2.8, 4, 6.25],
            y_values = [1, 3, 2.25, -1.5, 2.5, 1.75],
            line_color=GOLD_E,
            vertex_dot_style=dict(stroke_width=3,  fill_color=PURPLE),
            stroke_width = 4,
        )
        self.add(plane, line_graph)

在这里,我希望x轴和y轴在-2的地方交叉,也就是说,x轴应该在图表的底部。

1 个回答

0

看起来直接用NumberPlane的参数是无法做到这一点的。我找到了一种有点小技巧的方法来解决这个问题:

plane = NumberPlane(
            x_range = (0, 7),
            y_range = (-2, 5),
            x_length = 7,
            y_length = 5,
            axis_config={"include_numbers": True},
            y_axis_config={"numbers_to_exclude": [-2]}
        )
plane.center()
plane.x_axis.move_to(plane.coords_to_point(3.6, -2.2))
plane.y_axis.add_numbers([0])
y_label = plane.get_y_axis_label("\\text{Voltage [V]}", edge=LEFT, direction=LEFT, buff=0.4)
x_label = plane.get_x_axis_label("\\text{Time [$\mu$s]}", edge=DOWN, direction=DOWN, buff=0.4)
...

解决方案图片

我把y轴上的-2刻度去掉了,添加了0刻度。希望这样可以。

撰写回答