首页 > 解决方案 > Matplotlib 2 y 值针对每个 X

问题描述

我有 2 个 RMSE 值,我想使用库在y轴上针对x我持有的每个值绘制。matplotlib这是我目前的尝试:

def plotRMSE(rmses):
    #Both values in each subarray must be plotted on the y axis at the same x point
    #rmses = [[15, 30], [10, 25], [18.45, 23.1], [3.2, 6.36], [2.4, 1.86e-10], [1.627, 3.3e-10]]
    x = [0, 1, 2, 3, 5, 10]
    for i in range(len(x)):
        plt.scatter(x[i], rmses[i])
    plt.show()

这当然返回ValueError: x and y must be the same size。我找不到任何这样的例子(或任何其他合适的图表类型)。有比将每个值x[i]与每个子数组的两个值配对更好的解决方案吗?

编辑:我很傻。我可以在两个单独的电话中使用rmses[i][0]and 。这样做会导致不同的颜色点(我不想要;我希望每个点都用相同的颜色和图例标签表示),所以这是我完成的代码:rmses[i][1]plt.scatter()[0][1]

def plotRMSE(rmses):
    x = [0, 1, 2, 3, 5, 10]
    plt.xticks(x)
    for i in range(len(x)):
        plt.scatter(x[i], rmses[i][0], c="#555FFF")
        plt.scatter(x[i], rmses[i][1], c="#CC0000")
    plt.legend(["Train RMSE", "Test RMSE"])
    plt.show()

干杯。

标签: pythonnumpymatplotlib

解决方案


    def plotRMSE(rmses):
        #Both values in each subarray must be plotted on the y axis at the same x point

        x = [0, 1, 2, 3, 5, 10]
        for i in range(len(x)):
            print(x[i])
            print(rmses[i][0])
            plt.scatter(x[i], rmses[i][0])
            plt.scatter(x[i], rmses[i][1])
        plt.show()

rmses = [[15, 30], [10, 25], [18.45, 23.1], [3.2, 6.36], [2.4, 1.86e-10], [1.627, 3.3e-10]]

plotRMSE(rmses)

这是做你想做的吗?

在不改变数据格式的情况下,这似乎是最简单的解决方案,但是我通常会有两个响应 (y) 向量,y_1 和 y_2。然后做:

plt.scatter(x, y_1)
plt.scatter(x, y_2)
plt.show()

推荐阅读