Search code examples
rggplot2data-visualizationcrosstab

How do I adjust and remove the legend labels in my crosstab plot?


enter image description hereEssentially, I want the dot labeled 8 to read "Disliked" and 18 to read "Liked." I want to remove the other 4 points in my legend. I'm unsure how those managed to get there.

I've tried using the scale_fill_discrete() and scale_fill_manual(), but they're not working here. Any tips?

  #Load libraries
  library(ggplot2)
  library(dplyr)

  #Specify foods and countries
  foods <- c("cake", "cookies", "chocolate", "brownies")
  nations <- c("[![Belarus][1]][1]", "Zimbabwe", "Tanzania", "Morocco")

  #Create the data frame
  crosstab <- expand.grid(foods, nations)
  crosstab$value <- c(8, 8, 18, 18, 18, 18, 8, 18, 18, 18, 8, 18, 18, 8, 8, 18)

  #Plot the visualization
  final_plot <- ggplot(crosstab, aes(Var1, Var2)) + geom_point(aes(size = value), color = "#3484DA") + xlab("") + ylab("")

  #Add design elements
  final_plot + scale_size_continuous(range = c(5, 10)) +
    scale_x_discrete(position = "top") +
    theme(legend.position = "bottom",
          legend.title = element_blank(),
          legend.spacing.x = unit(0.1, "inches"),
          axis.text.x = element_text(size = 10.5, face = "bold"),
          axis.text.y = element_text(size = 10.5, face = "bold"),
          axis.ticks = element_blank(),
          panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          panel.background = element_blank())

Solution

  • You can add breaks and labels in your scale_size_continuous:

      final_plot + scale_size_continuous(range = c(5, 10), breaks = c(8,18), labels = c("Disliked","Liked")) +
        scale_x_discrete(position = "top") +
        theme(legend.position = "bottom",
              legend.title = element_blank(),
              legend.spacing.x = unit(0.1, "inches"),
              axis.text.x = element_text(size = 10.5, face = "bold"),
              axis.text.y = element_text(size = 10.5, face = "bold"),
              axis.ticks = element_blank(),
              panel.grid.major = element_blank(),
              panel.grid.minor = element_blank(),
              panel.background = element_blank())
    

    enter image description here

    Does it answer your question ?