我正在从ggplot2迁移到plotly,以便利用他们提供的互动功能。
我确实知道plotly库有一个ggplotly函数,我可以用来封装原生的ggplot命令,但我想学习如何使用原生的plotly命令绘制相似的图形。
我的问题是,我似乎无法按照ggplot2的方式绘制分组线。
mpg %>%
group_by(manufacturer, class) %>%
summarise(models=n())
|manufacturer |class | models|
|:------------|:----------|------:|
|audi |compact | 15|
|audi |midsize | 3|
|chevrolet |2seater | 5|
|chevrolet |midsize | 5|
|chevrolet |suv | 9|
|dodge |minivan | 11|
|dodge |pickup | 19|
|dodge |suv | 7|
|ford |pickup | 7|
|ford |subcompact | 9|
|ford |suv | 9|
|honda |subcompact | 9|
|hyundai |midsize | 7|
|hyundai |subcompact | 7|
|jeep |suv | 8|
|land rover |suv | 4|
|lincoln |suv | 3|
|mercury |suv | 4|
|nissan |compact | 2|
|nissan |midsize | 7|
|nissan |suv | 4|
|pontiac |midsize | 5|
|subaru |compact | 4|
|subaru |subcompact | 4|
|subaru |suv | 6|
|toyota |compact | 12|
|toyota |midsize | 7|
|toyota |pickup | 7|
|toyota |suv | 8|
|volkswagen |compact | 14|
|volkswagen |midsize | 7|
|volkswagen |subcompact | 6|
mpg %>%
group_by(manufacturer, class) %>%
summarise(models=n()) %>%
plot_ly(x=~class, y=~models, type="scatter", mode="lines+marker", color=~manufacturer)
与示例1的不同之处在于,我正在尝试按类而不是制造商进行分组。
mpg %>%
group_by(manufacturer, class) %>%
summarise(models=n()) %>%
plot_ly(x=~manufacturer, y=~models, type="scatter", mode="lines+marker", color=~class)
mpg %>%
group_by(manufacturer, class) %>%
summarise(models=n()) %>%
ggplot(aes(x=manufacturer, y=models, group=class, color=class)) +
geom_line() +
theme_minimal()
如何使示例2看起来像示例3?
答案 0 :(得分:4)
plotly
执行dplyr
group_by
事务的顺序很奇怪(我不应该这么认为)。也许这是一个错误,也许是某些我不知道的特征。
此时plotly
年轻,充满了意想不到的错误"像这样,所以要期望plotly
成为ggplot2
的完全替代品要非常谨慎,目前它还不是很接近,尽管它确实有一些很酷的功能。
这样就可以得到你想要的东西:
library(dplyr)
library(plotly)
mpg %>%
group_by(class,manufacturer) %>%
summarise(models=n()) %>%
plot_ly(x=~manufacturer, y=~models, group=~class,
type="scatter",color=~class, mode="lines+markers")
你尝试过的地方会让你一片空白:
library(dplyr)
library(plotly)
mpg %>%
group_by(manufacturer,class) %>%
summarise(models=n()) %>%
plot_ly(x=~manufacturer, y=~models, group=~class,
type="scatter",color=~class, mode="lines+markers")
出于某种奇怪的原因孤立这些行:
这是你的ggplot版本供参考:
mpg %>%
group_by(manufacturer, class) %>%
summarise(models=n()) %>%
ggplot(aes(x=manufacturer, y=models, group=class, color=class)) +
geom_line() + geom_point() +
theme_minimal()