8

I wish to plot the line chart using ggplotly and represent the numbers in percentage. So the ggplot command before or represents the figures in percentages and after or in decimals. The plots appear to be different. How can I make the plot using decimals and represent the tool tip labels in percentages?

library(plotly)
library(ggplot2)
library(devtools)
library(proto)
library(RColorBrewer)
library(gapminder)
library(stringr)
library(broom)
library(mnormt)

dat1 <- data.frame(
sex = factor(c("Female","Female","Male","Male")),
time = factor(c("Lunch","Dinner","Lunch","Dinner"), 
levels=c("Lunch","Dinner")),
total_bill = c(13.53, 16.81, 16.24, 17.42)
total_bill_pr = sprintf("%.0f%%", 100 * total_bill)
)

# Map sex to different point shape, and use larger points
p <- ggplot(data=dat1, aes(x=time, y=total_bill_pr, group=sex, shape=sex)) +
geom_line() +
geom_point()

p <- ggplotly(p)
p

or

 # Map sex to different point shape, and use larger points
p <- ggplot(data=dat1, aes(x=time, y=total_bill, group=sex, shape=sex)) +
geom_line() +
geom_point()

p <- ggplotly(p)
p
AK94
  • 325
  • 1
  • 5
  • 11
  • `total_bill_pr` is a factor, not a numeric variable! This is why you get two different plots. – Marco Sandri Aug 07 '17 at 08:21
  • Thank you so much Marco for replying, I would highly appreciate if you can correct this code as I have tried doing that but am not able to get it. the total_bill_pr is a character type variable that I see using str(total_bill_pr). – AK94 Aug 07 '17 at 08:29

1 Answers1

6

Here is a solution for your problem:

library(plotly)
library(ggplot2)

total_bill = c(13.53, 16.81, 16.24, 17.42)
dat1 <- data.frame(
sex = factor(c("Female","Female","Male","Male")),
time = factor(c("Lunch","Dinner","Lunch","Dinner"), levels=c("Lunch","Dinner")),
total_bill_no_pr = total_bill,
total_bill = sprintf("%.2f%%", total_bill)
)

# Use an additional "label" aesthetic
p <- ggplot(data=dat1, aes(x=time, y=total_bill_no_pr, 
            group=sex, shape=sex, label=total_bill)) +
     geom_line() + geom_point() + ylab("Total bill") + xlab("Time")

# Specify which aesthetic mappings to show in the tooltip 
p <- ggplotly(p, tooltip = c("x", "label", "group"))
p

enter image description here

A more flexible solution is:

# Use an additional "text" aesthetic
p <- ggplot(data=dat1, aes(x=time, y=total_bill_no_pr, group=sex, shape=sex,
            text=paste("Time:",time,"<br />Total bill:",total_bill,"<br />Sex:",sex))) +
     geom_line() + geom_point() + ylab("Total bill") + xlab("Time")

# Specify to show only the "text" aesthetic in the tooltip 
p <- ggplotly(p, tooltip = c("text"))
p

enter image description here

Marco Sandri
  • 23,289
  • 7
  • 54
  • 58