【发布时间】:2014-05-04 22:31:24
【问题描述】:
我有一些使用ggplot2 创建的图表,我想将其嵌入到 Web 应用程序中:我想使用工具提示来增强图表。我研究了几个选项。我目前正在尝试使用rCharts 库,其中包括凹坑图。
这是原始的ggplot:
这是将其转换为凹坑图的第一次尝试:
我有几个问题:
在用百分比格式化 y 轴后,数据会发生变化。
在格式化 x 轴以正确呈现日期后,打印的标签过多。
我不依赖于凹坑图表,所以如果有其他选项可以更轻松地调整轴格式,我很乐意知道。 (莫里斯图表看起来也不错,但调整它们看起来更难,不是吗?)
目标:修复坐标轴并添加提供日期(格式为 1984)和值(格式为 40%)的工具提示。
如果我能解决 1 和 2,我会很高兴。但如果有人有建议,还有另一个不太重要的问题:
我可以在将鼠标悬停在线条上时将线条标签(“前 10%”)添加到工具提示中吗?
从https://gist.github.com/ptoche/872a77b5363356ff5399下载数据后, 创建了一个数据框:
df <- read.csv("ps-income-shares.csv")
基本的凹坑图是通过以下方式创建的:
library("rCharts")
p <- dPlot(
value ~ Year,
groups = c("Fractile"),
data = transform(df, Year = as.character(format(as.Date(Year), "%Y"))),
type = "line",
bounds = list(x = 50, y = 50, height = 300, width = 500)
)
虽然基本,但到目前为止还不错。但是,以下旨在将 y 数据转换为百分比的命令会更改数据:
p$yAxis(type = "addMeasureAxis", showPercent = TRUE)
showPercent 我做错了什么?
供参考,这里是ggplot代码:
library("ggplot2")
library("scales")
p <- ggplot(data = df, aes(x = Year, y = value, color = Fractile))
p <- p + geom_line()
p <- p + theme_bw()
p <- p + scale_x_date(limits = as.Date(c("1911-01-01", "2023-01-01")), labels = date_format("%Y"))
p <- p + scale_y_continuous(labels = percent)
p <- p + theme(legend.position = "none")
p <- p + geom_text(data = subset(df, Year == "2012-01-01"), aes(x = Year, label = Fractile, hjust = -0.2), size = 4)
p <- p + xlab("")
p <- p + ylab("")
p <- p + ggtitle("U.S. top income shares (%)")
p
有关信息,上表基于 Thomas Piketty 和 Emmanuel Saez 在他们对美国最高收入者的研究中汇总的数据。数据等可以在他们的网站上找到,例如
http://elsa.berkeley.edu/users/saez/
编辑:
这是 Ramnath 解决方案的屏幕截图,添加了标题并调整了轴标签。谢谢拉姆纳特!
p$xAxis(inputFormat = '%Y-%m-%d', outputFormat = '%Y')
p$yAxis(outputFormat = "%")
p$setTemplate(afterScript = "
<script>
myChart.axes[0].timeField = 'Year'
myChart.axes[0].timePeriod = d3.time.years
myChart.axes[0].timeInterval = 10
myChart.draw()
myChart.axes[0].titleShape.remove() // remove x label
myChart.axes[1].titleShape.remove() // remove y label
myChart.svg.append('text') // chart title
.attr('x', 40)
.attr('y', 20)
.text('U.S. top income shares (%)')
.style('text-anchor','beginning')
.style('font-size', '100%')
.style('font-family','sans-serif')
</script>
")
p
更改(而不是删除)轴标签,例如:
myChart.axes[1].titleShape.text('Year')
要为绘图添加图例:
p$set(width = 1000, height = 600)
p$legend(
x = 580,
y = 0,
width = 50,
height = 200,
horizontalAlign = "left"
)
保存 rchart:
p$save("ps-us-top-income-shares.html", cdn = TRUE)
可以通过以下方式获得基于 nvd3 库的替代方案(没有任何花哨的东西):
df$Year <- strftime(df$Year, format = "%Y")
n <- nPlot(data = df, value ~ Year, group = 'Fractile', type = 'lineChart')
【问题讨论】:
标签: r ggplot2 rcharts morris.js dimple.js