R graph more questions about parametrization

2019-08-24 18:27发布

I have built this graph in R:

library(ggplot2)

dataset <- data.frame(Riserva_Riv_Fine_Periodo = 1:10 * 10^6 + 1,
                      Anno = 1:10)

ggplot(data = dataset, 
            aes(x = Anno, 
                y = Riserva_Riv_Fine_Periodo)) + 
  geom_bar(stat = "identity", 
           width=0.8, 
           position="dodge") + 
  geom_text(aes( y = Riserva_Riv_Fine_Periodo,
            label = round(Riserva_Riv_Fine_Periodo, 0), 
                 angle=90, 
                 hjust=+1.2), 
            col="white", 
            size=4, position = position_dodge(0.9))

enter image description here

As you can see I have 2 issue:

  1. the numbers into the bars are truncated.
  2. The y scale is written in this format "0e+00"

I'd like to:

  1. Set the numbers inside or outside the bar according to the height of the bar
  2. Set the y scale in million.

标签: r ggplot2
1条回答
Luminary・发光体
2楼-- · 2019-08-24 18:37
  1. You can use an ifelse statement to conditionally change the hjust argument based on the value of the y
  2. You can change how R represents decimals using the scipen option.

Here is an example:

library(ggplot2)

options(scipen=2)

dataset <- data.frame(Riserva_Riv_Fine_Periodo = 1:10 * 10^6 + 1,
                      Anno = 1:10)

ggplot(data = dataset, 
            aes(x = Anno, 
                y = Riserva_Riv_Fine_Periodo)) + 
  geom_bar(stat = "identity", 
           width=0.8, 
           position="dodge") + 
  geom_text(aes( y = Riserva_Riv_Fine_Periodo,
                 label = round(Riserva_Riv_Fine_Periodo, 0), 
                 angle=90, 
                 hjust= ifelse(Riserva_Riv_Fine_Periodo < 3000000, -0.1,  1.2)), 
            col="red", 
            size=4, 
            position = position_dodge(0.9))

enter image description here

查看更多
登录 后发表回答