0

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])
  })
  • Welcome to SO! To help us to help you could you please make your issue reproducible by sharing a sample of your **data**, a working **code** example and the **packages** you used? See [how to make a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) To post your data type `dput(NAME_OF_DATASET)` into the console and copy & paste the output starting with `structure(....` into your post. – stefan May 30 '21 at 12:40

1 Answers1

1

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.

Brenton M. Wiernik
  • 1,006
  • 4
  • 8
  • Thank you so much. I tried your example and I got the same output so I started to search the problem elsewhere. Finally, the problem appears when I wrap ggplot object inside a plotly wrapper, so it is not a ggplot fault, but plotly one. – WildParamecium May 30 '21 at 14:05