0

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.
Michael Harper
  • 14,721
  • 2
  • 60
  • 84
  • Please make sure to include a dataset with your question so that others may be able to rebuild your dataset. Check here for some more details: https://stackoverflow.com/q/5963269/7347699 – Michael Harper Apr 16 '18 at 14:43
  • 1
    Please also try and keep questions on stackoverflow to a single issues. Setting the labels and changing the scale are two separate problems. Relating to the change of scales, this should help:https://stackoverflow.com/questions/4646020/ggplot2-axis-transformation-by-constant-factor – Michael Harper Apr 16 '18 at 14:46

1 Answers1

0
  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

Michael Harper
  • 14,721
  • 2
  • 60
  • 84
  • Thank you Mikey. The scipen option is fine! The solution with l'ifelse is fine too but I need to make "dinamic" the range of the condition. Any ideas? thank you – Lara Braghetti Apr 16 '18 at 15:27
  • No problem @LaraBraghetti. Please mark the answer as accepted and upvote if you are satisfied :) – Michael Harper Apr 16 '18 at 15:28