Search code examples
rggplot2plotlytidyversedata-visualization

How to put 3rd variable on right axis in Horizontal dots plot?


I have horizontal dots plot visualized by Plotly in R. My data set contains 3 numerical and 1 categorical variable.

'origin' is on y-axis. 'change' and 'rate' variables are visualized into circles. Now I want to put 'Percentage' variable on right axis in the circles

    df <- data.frame (origin = c("A","B","C","D","E","F","G","H","I","J"),
                  Percentage = c(23,16,32,71,3,60,15,21,44,60),
                  rate = c(10,12,20,200,-25,12,13,90,-105,23),
                  change = c(10,12,-5,12,6,8,0.5,-2,5,-2))

library(ggplot2)

ggplot(df, aes(x = rate, y = factor(origin, rev(origin)))) +
  geom_hline(aes(yintercept = origin), color = 'gray') +
  geom_vline(xintercept = 0, linetype = 2, color = 'gray') +
  geom_point(aes(color = 'Rate'), size = 10) +
  geom_text(aes(label = rate), color = 'white') +
  geom_point(aes(x = change, color = 'Change'), size = 10) +
  geom_text(aes(label = change, x = change)) +
  theme_minimal(base_size = 16) +
  scale_x_continuous(labels = ~paste0(.x, '%'), name = NULL) +
  scale_color_manual(values = c('#aac7c4', '#5f9299')) +
  theme(panel.grid = element_blank(),
        axis.text.y = element_text(color = 'gray50')) +
  labs(color = NULL, y = NULL)

Output: enter image description here

Expected Output:

enter image description here


Solution

  • You could do

    ggplot(df, aes(x = rate, y = factor(origin, rev(origin)))) +
      geom_hline(aes(yintercept = origin), color = 'gray') +
      geom_vline(xintercept = 0, linetype = 2, color = 'gray') +
      geom_point(aes(color = 'Rate'), size = 10) +
      geom_text(aes(label = rate), color = 'white') +
      geom_point(aes(x = change, color = 'Change'), size = 10) +
      geom_text(aes(label = change, x = change)) +
      geom_point(aes(x = 220, fill = "Percentage"), color = "blue",
                 size = 12, shape = 21) +
      geom_text(aes(x = 220, label = paste0(Percentage, "%"))) +
      theme_minimal(base_size = 16) +
      scale_x_continuous(labels = ~paste0(.x, '%'), name = NULL) +
      scale_color_manual(values = c('#aac7c4', '#5f9299')) +
      scale_fill_manual(values = "white", name = NULL) +
      theme(panel.grid = element_blank(),
            axis.text.y = element_text(color = 'gray50')) +
      coord_cartesian(xlim = c(-120, 230), ylim = c(0, 11),
                      expand = FALSE) +
      labs(color = NULL, y = NULL)
    

    enter image description here