Search code examples
rggplot2colorscrosstabbubble-chart

Visualizing crosstab tables with a plot in R - changing colours


I have the following code in R which is modified from here, which plots a crosstab table:

#load ggplot2
library(ggplot2)                           

# Set up the vectors                           
xaxis <- c("A", "B")
yaxis <- c("A","B")

# Create the data frame
df <- expand.grid(xaxis, yaxis)
df$value <- c(120,5,30,200)    

#Plot the Data
g <- <- ggplot(df, aes(Var1, Var2)) + geom_point(aes(size = value), colour = "lightblue") + theme_bw() + xlab("") + ylab("") 
g + scale_size_continuous(range=c(10,30)) + geom_text(aes(label = value))

It produces the right figure, which is great, but I was hoping to custom colour the four dots, ideally so that the top left and bottom right are both one colour and the top right and bottom left are another.

I have tried to use:

+ scale_color_manual(values=c("blue","red","blue","red"))

but that doesn't seem to work. Any ideas?


Solution

  • I would suggest that you colour by a vector in your data frame, as you don't have a column that gives you this, you can either create one, or make a rule based on existing columns (which I have done below):

    g <- ggplot(df, aes(Var1, Var2)) + geom_point(aes(size = value, colour = (Var2!=Var1))) + theme_bw() + xlab("") + ylab("") 
    g + scale_size_continuous(range=c(10,30)) + geom_text(aes(label = value))
    

    The important part is: colour = (Var2!=Var1), note that i put this inside the aesthetic (aes) for the geom_point

    Edit: if you wish to remove the legend (you annotate the chart with totals, so I guess you don't really need it), you can add: g + theme(legend.position="none") to remove it