I'm trying to produce a scatter plot with ggplot for a shiny web app, to show the relationship between two variables(age and platelets, both numeric). Moreover, I want to add two additional dimensions to show possible differences in the linear relationship, plotted with color and shape (diabetes and anemia, both factor variables with possible values 0 or 1).
#selected() is a reactive function that apply filters to the dataframe
ggplot(data = selected(), aes(x=age, y=platelets, shape=diabetes, color=anaemia)) + geom_point()
This chunk of code is returning the following legend:
diabetes
0
(0,1)
(1,0)
1
And I was expecting the following output instead:
diabetes
0
1
anaemia
0
1
I have been reading at ggplot documentation but I didnt find a way to solve this problem. I really appreciate possible help to solve the problem.
Edit: Dataset: https://www.kaggle.com/andrewmvd/heart-failure-clinical-data
selected() function body
selected <- reactive({
heart %>%
select(c(input$variables, response))
filter(age >= input$age[1], age <= input$age[2])
})
ggplot2's default behavior is to have separate guides for each variable like you want. See the example below with code that is equivalent to what you have written.
library(ggplot2)
ggplot(data = mtcars) +
aes(x = wt, y = mpg, shape = factor(am), color = factor(vs)) +
geom_point()
Created on 2021-05-30 by the reprex package (v2.0.0)
Is the code you showed actually what you are running that produces a different legend? If so, please post a reproducible example showing what happens.