我想在下面的图中添加一个图例。该图创建两个序列(表示概率质量函数)。无论如何,我想有一个传说,“观察”的红色系列和“理论”的黑色系列。下面的代码应该使用来自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())
2条答案
按热度按时间1l5u6lss1#
您需要重新构造数据,使其只有两个系列(红色和黑色),并添加一个分组变量:
然后将“颜色”美学Map到分组变量:
1u4esq0p2#
如果你想在更高的图表中使用lengends,你可以这样写