如何将颜色条放入matplotlib图例

时间:2018-12-20 18:11:01

标签: python matplotlib colorbar

我有生成此图的代码: enter image description here

在此图中,颜色表示每条线下端的水平偏移。我希望在图例中显示一个颜色条(带有“开始”和“停止”),以显示颜色的含义。

这是我的代码:

import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx


plt.clf()
plt.plot([0,100], [0,100], '--', linewidth=3, color='k', label = 'start')
plt.plot([100,100],[0,100], '-.', linewidth=3, color = 'k', label = 'stop')



jet = plt.get_cmap('jet') 
cNorm  = colors.Normalize(vmin=0, vmax=99)
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)

for offset in range(1,100):
    colorVal = scalarMap.to_rgba(offset)
    plt.plot([offset, 100], [0,100], color=colorVal)

plt.legend()
plt.show()

因此,理想情况下,我会看到类似标准颜色条的颜色,其范围从0到100,但出现在图例中并带有标签'offset'

1 个答案:

答案 0 :(得分:2)

这里有一些代码基于ImportanceOfBeingErnest的注释方法(2)来完成此任务。

buildscript {
    ext {
        springBootVersion = '2.1.1.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    implementation('org.springframework.boot:spring-boot-starter-data-jpa')
    runtime('com.h2database:h2')
    compileOnly('org.projectlombok:lombok')
    compileOnly ('org.hibernate:hibernate-jpamodelgen')
    testImplementation('org.springframework.boot:spring-boot-starter-test')
}

// Add source set to define where the generated source code should go to
sourceSets.configureEach { sourceSet ->
    tasks.named(sourceSet.compileJavaTaskName).configure {
        options.annotationProcessorGeneratedSourcesDirectory = file("$buildDir/generated/sources/java")
    }
}

screen shot