带有facet_grid的ggplot2柱形图

时间:2015-10-07 05:00:23

标签: r ggplot2

我正在尝试制作一个R ggplot2图表,其中列分组一个变量,facet_grid分解另一个变量。我试过的两种方式都失败了:

1)将x设置为facet_grid变量按该变量分解两次:

ggplot(diamonds, aes(x=cut, y=price, fill=color)) +
    geom_bar(position="dodge", stat="identity") +
    facet_grid(cut ~ ., scales="free")

enter image description here

2)删除x会产生错误:

ggplot(diamonds, aes(y=price, fill=color)) +
    geom_bar(position="dodge", stat="identity") +
    facet_grid(cut ~ ., scales="free")
# Error in exists(name, envir = env, mode = mode): 
# argument "env" is missing, with no default

1 个答案:

答案 0 :(得分:5)

x设置为与color arg:

相同的变量
ggplot(diamonds, aes(x=color, y=price, fill=color)) +
    geom_bar(position="dodge", stat="identity") +
    facet_grid(cut ~ ., scales="free")

enter image description here