如何在不基于数据Map的情况下添加图例来绘制Kotlin

t40tm48m  于 2023-10-23  发布在  Kotlin
关注(0)|答案(2)|浏览(113)

我想在下面的图中添加一个图例。该图创建两个序列(表示概率质量函数)。无论如何,我想有一个传说,“观察”的红色系列和“理论”的黑色系列。下面的代码应该使用来自Kotlinlets-plot的适当导入来运行。我能找到的所有例子都有基于数据序列的图例。我还没有找到任何例子,可以给予我如何做到这一点的见解。

val dataMap = mapOf(
        "estimated" to listOf(0.2, 0.3, 0.4, 0.1),
        "observed" to listOf(1, 2, 3, 4),
        "probability" to listOf(0.19, 0.31, 0.42, 0.08),
        "values" to listOf(1, 2, 3, 4),
    )
    val pd = positionNudge(.1)
    var p = ggplot(dataMap) + theme().legendPositionRight() +
            geomPoint(color = "red", position = pd) {
                x = "observed"
                y = "estimated"
            } +
            geomPoint(color = "black") {
                x = "values"
                y = "probability"
            }
    for (i in 1..4) {
        p = p + geomSegment(yend = 0, color = "red", position = pd) {
            x = "observed"
            y = "estimated"
            xend = "observed"
        }
    }
    for (i in 1..4) {
        p = p + geomSegment(yend = 0, color = "black") {
            x = "values"
            y = "probability"
            xend = "values"
        }
    }
    p = p + labs(title = "some title", x = "xLabel", y = "yLabel") +
            ggsize(500, 350)

    val spec = p.toSpec()
    // Export: use PlotHtmlExport utility to generate dynamic HTML (optionally in iframe).
    val html = PlotHtmlExport.buildHtmlFromRawSpecs(
        spec, iFrame = true,
        scriptUrl = PlotHtmlHelper.scriptUrl(VersionChecker.letsPlotJsVersion)
    )
    val tmpDir = File("someDirectory")
    if (!tmpDir.exists()) {
        tmpDir.mkdir()
    }
    val file = File.createTempFile("someFileName", ".html", tmpDir)
    FileWriter(file).use {
        it.write(html)
    }
    val desktop = Desktop.getDesktop()
    desktop.browse(file.toURI())
1l5u6lss

1l5u6lss1#

您需要重新构造数据,使其只有两个系列(红色和黑色),并添加一个分组变量:

val estimated = listOf(0.2, 0.3, 0.4, 0.1)
val observed = listOf(1, 2, 3, 4) 
val probability = listOf(0.19, 0.31, 0.42, 0.08)
val values = listOf(1, 2, 3, 4)

val data = mapOf(
    "xs" to observed + values,
    "ys" to estimated + probability,
    "group" to List(4) {"A"} + List(4) {"B"}
)

然后将“颜色”美学Map到分组变量:

var p = ggplot(data) + theme().legendPositionRight() +
    geomLollipop(position = positionDodge(0.3)) {
        x = "xs"
        y = "ys"
        color = "group"
    } + scaleColorManual(values=listOf("red", "black"))
    
p = p + labs(title = "some title", x = "xLabel", y = "yLabel") +
            ggsize(500, 350)

1u4esq0p

1u4esq0p2#

如果你想在更高的图表中使用lengends,你可以这样写

val legend = HILegend()
        legend.enabled = true
        options.legend = legend

相关问题