Matplotlib基于xaxis上的值使用多种颜色绘制

2024-10-04 05:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到一个与下面的图类似的图,它根据x轴的值有不同的颜色。忽略u和f字母以及蓝色曲线和灰色线条。我只需要绿线和红线。所以,如果你用我的代码,你会得到一个只有一种颜色的图。我想要的是当x在0和转折点之间时有不同的颜色(在本例中是x=50%),然后对其余的使用不同的颜色。在

代码:

import matplotlib.pyplot as plt

def GRLC(values):
    n = len(values)
    assert(n > 0), 'Empty list of values'
    sortedValues = sorted(values) #Sort smallest to largest

    #Find cumulative totals
    cumm = [0]
    for i in range(n):
        cumm.append(sum(sortedValues[0:(i + 1)]))

    #Calculate Lorenz points
    LorenzPoints = [[], []]
    sumYs = 0           #Some of all y values
    robinHoodIdx = -1   #Robin Hood index max(x_i, y_i)
    for i in range(1, n + 2):
        x = 100.0 * (i - 1)/n
        y = 100.0 * (cumm[i - 1]/float(cumm[n]))
        LorenzPoints[0].append(x)
        LorenzPoints[1].append(y)
        sumYs += y
        maxX_Y = x - y
        if maxX_Y > robinHoodIdx: robinHoodIdx = maxX_Y   

    giniIdx = 100 + (100 - 2 * sumYs)/n #Gini index 

    return [giniIdx, giniIdx/100, robinHoodIdx, LorenzPoints]

reg=[400,200]
result_reg = GRLC(reg)
print 'Gini Index Reg', result_reg[0]  
print 'Gini Coefficient Reg', result_reg[1]
print 'Robin Hood Index Reg', result_reg[2]

#Plot
plt.plot(result_reg[3][0], result_reg[3][1], [0, 100], [0, 100], '--')

plt.legend(['Reg-ALSRank@10','Equity-Line'], loc='upper left',prop={'size':16})
plt.xlabel('% of items ')
plt.ylabel('% of times being recommended')
plt.show()

Tags: of颜色pltresultregvaluesappendgini
1条回答
网友
1楼 · 发布于 2024-10-04 05:27:01

这是如何绘制两行不同颜色的线,知道数组中颜色应该改变的索引。在

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,49, num=50)
y = x**2

x0 = 23

plt.plot(x[:x0+1], y[:x0+1])
plt.plot(x[x0:], y[x0:])
plt.show()

enter image description here

这是因为默认情况下,后续的线条图有不同的颜色,但您当然可以自己设置颜色

^{pr2}$

相关问题 更多 >