4
votes

I have the following dataframe:

    df <- data.frame(party=c("Democrat", "Democrat", "Democrat", "Republican","Republican","Republican","Republican","Republican","Democrat","Democrat"), value=c(1,4,2,3,5,6,10,9,8,7), year=c(1960:1969))

I am attempting to plot year on the x axis, value on the y axis, and color by party. So the ggplot version is straightforward and it works:

    library(ggplot2)
    library(plotly)

    p<-ggplot(df, aes(x=year, y=value, color=party, group=1))+geom_line()
    p

enter image description here

My problem is when trying to convert this to a plotly object using ggplotly.

    ggplotly(p)

enter image description here

It seems that the group=1 option in the ggplot aesthetics that forces the line to be a single line that is segmented by color doesn't carry over to ggplotly at all. Can anyone point to a way to fix this? I've searched for a few hours now, to no avail.

1

1 Answers

3
votes

I'd suggest swapping out geom_line for geom_segment, which lets you define the appearance of each line segment. It needs the endpoint for each segment, but it survives the translation into plotly, which seems to have a slightly different model than ggplot2 does for dealing with multiple series.

q<-ggplot(df, aes(x=year, y=value, 
                  xend = lead(year), yend = lead(value),
                  color=party))+
  geom_segment() + 
  scale_x_continuous(breaks = seq(1960, 1970, by = 2))
q

ggplotly(q)

enter image description here