我想获得这段代码给出的相同图形:
library(ggplot2)
name <- c("A","A","A","A","B","B","B","B")
size <- c("small","small","tall","tall","small","small","tall","tall")
flag <- c(0,1,0,1,0,1,0,1)
quantity <- c(26,13,12,4,19,14,13,5)
df <- data.frame(name,size,flag,quantity)
ggplot(data = df, mapping = aes(x = name, y = quantity)) +
geom_bar(aes(fill = size), position = "dodge", stat = "identity")
除了我希望根据可变标志拆分小节。理想的做法是使与flag = 0
对应的条形部分具有不同的颜色阴影。
我还需要标记变量的图例。
答案 0 :(得分:2)
为标志使用不同的alpha值:
这将为标志添加不同的透明度值。但是,所有酒吧都是躲闪的。
ggplot(data = df, mapping = aes(x = name, y = quantity)) +
geom_bar(aes(fill = size, alpha = factor(flag)), position = "dodge", stat = "identity") +
scale_alpha_manual("flag", values = c(0.3, 1))
facet_wrap
与x轴上的交互作用(名称,大小)的组合:
将条形图的堆叠尺寸保持相同,需要解决方法以使x轴更好。
ggplot(data = df, mapping = aes(x = interaction(name, size), y = quantity)) +
geom_bar(aes(fill = size, alpha = factor(flag)),
position = "stack", stat = "identity") +
scale_alpha_manual("flag", values = c(0.3, 1)) +
facet_wrap(~ name, strip.position = "bottom", scales = "free_x") +
theme(axis.ticks.x = element_blank(),
axis.text.x = element_blank(),
axis.title.x = element_blank(),
strip.background = element_blank())
大小互动:
通过指定scale_fill_manual
,您可以为大小和标志的不同组合分配不同的颜色。
ggplot(data = df, mapping = aes(x = name, y = quantity)) +
geom_bar(aes(fill = interaction(size, flag)), position = "dodge", stat = "identity")
答案 1 :(得分:1)
library(ggplot2)
df1 <- data.frame(name = c("A","A","A","A","B","B","B","B"),
size = c("small","small","tall","tall","small","small","tall","tall"),
flag = c(0,1,0,1,0,1,0,1),
quantity = c(26,13,12,4,19,14,13,5))
ggplot(data = df1, mapping = aes(x = name, y = quantity)) +
geom_bar(aes(fill = size), alpha = ifelse(flag==0, 0.6, 1),
position = "dodge", stat = "identity")
在 @kath 答案的顶部添加:
library(grid)
library(ggplot2)
gg_color_hue <- function(n) {
hues = seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
mycols <- gg_color_hue(length(unique(interaction(df$size, df$flag)))/2)
ggplot(data = df, mapping = aes(x = interaction(name, size), y = quantity)) +
geom_bar(aes(fill = interaction(factor(size), factor(flag))),
position = "stack", stat = "identity") +
scale_fill_manual(name = "Size and Flag",
values = c("small.0" = alpha(mycols[1], 3/5),
"tall.0" = alpha(mycols[2], 3/5),
"small.1" = alpha(mycols[1], 1),
"tall.1" = alpha(mycols[2], 1)),
labels = c("Size: small and Flag: 0",
"Size: tall and Flag: 0",
"Size: small and Flag: 1",
"Size: tall and Flag: 1")) +
facet_wrap(~ name, strip.position = "bottom", scales = "free_x") +
theme(axis.ticks.x = element_blank(),
axis.text.x = element_blank(),
strip.background = element_blank(),
panel.spacing = unit(-1.25, "lines")) +
xlab("name")