【问题标题】:How to manually place labels on Y-Axis without placing space in matplotlib如何在 Y 轴上手动放置标签而不在 matplotlib 中放置空间
【发布时间】:2017-03-25 17:19:16
【问题描述】:

我正在尝试在一个图形上绘制两个数据点图,并且我已经完成了这项任务,我正在使用 Python 和 Matplotlib 来完成这项任务。 但是当我想将文本添加到 ylabel 时,问题就来了,添加文本很简单,但我想添加与我的图表相邻的文本,而且也不使用空格。 目前我正在使用空格,但是当数字缩小到不同的大小时这会产生问题,我希望有另一种更好的方法来做到这一点。 我将我的问题分解为简单的场景,代码如下:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.gca()

# Sampling Frequency
SampleFreq = 500.0
time_axis = np.arange(0, 1.0, 1/SampleFreq)

sin_sig = np.sin(2 * np.pi * 10 * time_axis) + 2.0
cos_sig = np.cos(2 * np.pi * 10 * time_axis)

plt.plot(time_axis, sin_sig ,color='#000080', linewidth=1.0)
plt.plot(time_axis, cos_sig ,'r', linewidth=1.0)
plt.xlim(0, 1.0)
plt.yticks([])
plt.grid()
plt.xlabel('Time in ms', fontweight='bold')
plt.ylabel('Cos Signal                    \
                    Sine Signal',fontweight='bold')
plt.show()

如图所示,正弦和余弦信号写在 ylabel 上,但它们是通过使用空格来调整的。

我希望有人可以帮助找到正确的解决方案。 提前致谢

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您可以创建两个子图,每条曲线一个,但具有不同的 ylabel。

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, (ax,ax2) = plt.subplots(nrows=2, sharex=True)
    plt.subplots_adjust(hspace=0)
    
    
    # Sampling Frequency
    SampleFreq = 500.0
    time_axis = np.arange(0, 1.0, 1/SampleFreq)
    
    sin_sig = np.sin(2 * np.pi * 10 * time_axis)
    cos_sig = np.cos(2 * np.pi * 10 * time_axis)
    
    ax2.plot(time_axis, sin_sig ,color='#000080', linewidth=1.0)
    ax.plot(time_axis, cos_sig ,'r', linewidth=1.0)
    ax2.set_xlim(0, 1.0)
    for a in [ax,ax2]:
        a.set_yticks([-1,1])
        a.set_yticklabels(["off", "on"])
        a.grid(True, axis='x',)
    
    
    ax2.set_xlabel('Time in ms', fontweight='bold')
    ax.set_ylabel("Sine Signal",fontweight='bold')
    ax2.set_ylabel("Cos Signal",fontweight='bold')
    
    ax.spines['bottom'].set_visible(False)
    ax2.spines['top'].set_visible(False)
    
    plt.show()
    

    【讨论】:

    • 谢谢,你拯救了我的一天,非常感谢。我还想问一个问题,是否也可以在 yticks 上加上一些文本,例如在 ax 轴上 -1 为关闭,+1 为开启
    猜你喜欢
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多