ggplot2 / barplot / get bars close / adjustment" width"不起作用

时间:2017-01-10 23:01:51

标签: r

请帮助让两个酒吧靠近。我玩过"宽度"现在整天都在geom_barposition_dodge中运行,但没有成功。提前致谢。

我的数据:

race  rate
1     11.860087
2     8.894954

我的代码:

ggplot(visrate, aes(factor(race), rate, fill=race, label=sprintf("%0.1f", round(rate, digits = 1)))) +
    geom_bar(stat="identity", width=0.25, position = position_dodge(width = 0.01)) +
    scale_fill_brewer(palette="Set1") +
    scale_fill_discrete(name="Race", breaks=c("1", "2"),labels=c("Caucasian", "African-American")) +
    scale_y_continuous(name = "Pancreatic Cancer Hospitalization Rate, 1995-2013",limits = c(0, 12),breaks = seq(0, 12, by = 2)) +
    ggtitle("Pancreatic Cancer Hospitalizations by Race") +
    theme(text=element_text(size = 10, family="courier")) +
    geom_text(size = 4, hjust = 0.5, vjust=1.5) + 
    theme(axis.title.x=element_blank(),axis.text.x=element_blank(),axis.ticks.x=element_blank())

Barplot

1 个答案:

答案 0 :(得分:1)

您不需要躲闪情节 - 当您在同一个x轴位置多个条时,会使用位置躲避。在这里,你有两个x轴值和两个条形,不需要闪避。

geom_bar内,width指的是条之间的空间百分比是“满栏”。你有width = 0.25,所以酒吧占据了25%的空间。如果您希望条形触摸设置width = 1。如果您希望他们几乎触摸使用width = 0.9

此外,正如评论中所指出的,在情节中只会使用一个scale_fill。如果添加两个,则第一个将被忽略。并且您应该始终使用race作为因素(最好是事先在数据框中更改它)。

ggplot(visrate, aes(factor(race), rate, fill = factor(race), label=sprintf("%0.1f", round(rate, digits = 1)))) +
    geom_bar(stat= "identity", width = 1) +
    scale_fill_discrete(name="Race", breaks=c("1", "2"),labels=c("Caucasian", "African-American")) +
    scale_y_continuous(name = "Pancreatic Cancer Hospitalization Rate, 1995-2013", limits = c(0, 12), breaks = seq(0, 12, by = 2)) +
    ggtitle("Pancreatic Cancer Hospitalizations by Race") +
    theme(text=element_text(size = 10, family="courier")) +
    geom_text(size = 4, hjust = 0.5, vjust=1.5) + 
    theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank())