【发布时间】:2016-12-08 17:02:49
【问题描述】:
我在ggplot2 绘图中具有以下功能。该函数的一个特点是调用str_wrap 函数来处理我拥有的很长的标签。
PlotResponseRate <- function(EntryData)
{
PlotData <- as.data.frame(apply(X = EntryData, MARGIN = 2,
function(x) round(length(which(!is.na(x)))/length(x)*100)))
colnames(PlotData) <- "TheData"
PlotData$TheLabel <- factor(str_wrap(colnames(EntryData), width = 30),
levels = unique(str_wrap(colnames(EntryData), width = 30)))
Graphe <- ggplot(data = PlotData, aes(x = TheLabel, y = TheData)) +
geom_bar(stat = "identity", fill = "red", width = 0.8) +
coord_flip() +
labs(title = "Response rate")
}
它在“普通”R 环境中运行良好,我想将它与plotly 一起使用。因此,我添加以下代码行:
PlotData$TheLabel <- gsub(pattern = "\n", replacement = "\n<br>", PlotData$TheLabel)
它似乎有效,但仍然存在问题:绘图左侧的空间太宽(我不确定,但看起来它与长标签的空间相同)。
如何避免这种行为?
这是一个简单的例子:
library(stringr)
library(ggplot2)
library(plotly)
a <- c(1, 2, 2, 2, NA, 1, 2, 2, 1)
b <- c(2, 1, 2, NA, 2, NA, 1, NA, 1)
df <- data.frame(a, b)
colnames(df) <- c("This Is A Long Answer To A Long Question Label For The First Question",
"This Is A Long Answer To A Long Question Label For The Second Question")
TheGgplot2Plot <- PlotResponseRate(df)
ThePlotlyPlot <- ggplotly(TheGgplot2Plot)
print(ThePlotlyPlot)
【问题讨论】: