【问题标题】:Add a string to an x-axis of integers将字符串添加到整数的 x 轴
【发布时间】:2017-09-06 17:38:12
【问题描述】:

我在 x 轴(溶液浓度)上针对效率 (y) 绘制图表。我已将此设置为在 0 到 100 之间显示 x,但我想添加另一个数据点作为控件,根本没有任何解决方案。我遇到了问题,因为这实际上并不适合浓度轴上的任何位置,但我想在 0 之前或 100 之后添加它,可能会在轴上中断以将它们分开。所以我的 x 轴看起来像 ['control', 0, 20, 40, 60, 80, 100]

MWE:

x_array = ['control', 0, 20, 40, 50, 100]
y_array = [1, 2, 3, 4, 5, 6]
plt.plot(x_array, y_array)

尝试这个,我得到一个错误:

ValueError: 无法将字符串转换为浮点数:'control'

有什么想法可以让我做这样的事情吗?我查看了 xticks 但这会将 x 轴绘制为字符串,因此失去了轴的连续性,由于数据点的间距不等距,这会弄乱绘图。

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    您可以将单个点添加到图表中,作为对 plot 的单独调用,然后调整 x 轴标签。

    import matplotlib.pyplot as plt
    
    x_array = [0, 20, 40, 50, 100]
    y_array = [2, 3, 4, 5, 6]
    x_con = -20
    y_con = 1
    x_ticks = [-20, 0, 20, 40, 60, 80, 100]
    x_labels = ['control', 0, 20, 40, 60, 80, 100]
    
    fig, ax = plt.subplots(1,1)
    ax.plot(x_array, y_array)
    ax.plot(x_con, y_con, 'ro')  # add a single red dot
    
    # set tick positions, adjust label text
    ax.xaxis.set_ticks(x_ticks)
    ax.xaxis.set_ticklabels(x_labels)
    ax.set_xlim(x_con-10, max(x_array)+3)
    ax.set_ylim(0,7)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多