请考虑以下几行.
p <- ggplot(mpg, aes(x=factor(cyl), y=..count..))
p + geom_histogram()
p + stat_summary(fun.y=identity, geom='bar')
Run Code Online (Sandbox Code Playgroud)
理论上,最后两个应该产生相同的情节.在实践中,stat_summary失败并抱怨所需的美学缺失.
为什么我不能用..count..的stat_summary?我在文档中找不到有关如何使用这些变量的信息.
ggplot2中的stats_函数创建特殊变量,例如stat_bin2d创建一个名为的特殊变量..count...在哪里可以找到列出哪个stat_函数返回哪些特殊变量的文档?
我查看了主要的ggplot2 文档页面和R在线帮助.我试过读一下stat_bin2d的源代码,但它使用了我不懂的语言 - 我不知道如何得到后面的代码StatBin2d$new(...).
我想做的是以某种方式同时使用position = "fill"和的position = "dodge"参数。geom_bar()使用一些样本数据
set.seed(1234)
df <- data.frame(
Id = rep(1:10, each = 12),
Month = rep(1:12, times = 10),
Value = sample(1:2, 10 * 12, replace = TRUE)
)
Run Code Online (Sandbox Code Playgroud)
我能够创建以下图表
df.plot <- ggplot(df, aes(x = as.factor(Month), fill = as.factor(Value))) +
geom_bar(position = "fill") +
scale_x_discrete(breaks = 1:12) +
scale_y_continuous(labels = percent) +
labs(x = "Month", y = "Value")
Run Code Online (Sandbox Code Playgroud)
我喜欢这个图的缩放和标签,但我希望能够将其拆开。但是当我执行以下操作时
df.plot2 <- ggplot(df, aes(x = as.factor(Month), fill = as.factor(Value))) +
geom_bar(position = "dodge", …Run Code Online (Sandbox Code Playgroud) 我想要一个堆叠的条形图,其中包含基于计数的百分比。我几乎达到了我想要的,但文本中的每个值都是 100% 而不是实际百分比......我认为我的代码中有一个小错误,但我找不到它。
ggplot(
mtcars,
aes(fill = factor(gear),
x = factor(carb))
) +
geom_bar(stat = "count",
position = "fill",
color = "black",
width = 0.5) +
geom_text(aes(label = scales::percent(..prop..)),
position = position_fill(vjust = 0.5),
stat = "count") +
coord_flip()
Run Code Online (Sandbox Code Playgroud)