2017-09-14 120 views
1

好奇如何使用ggplot或plotly库函数来绘制这个dotplot。还要在各个点上标记mpg值。gplot版dotplot

# Dotplot: Grouped Sorted and Colored 
# Sort by mpg, group and color by cylinder 
x <- mtcars[order(mtcars$mpg),] # sort by mpg 
x$cyl <- factor(x$cyl) # it must be a factor 
x$color[x$cyl==4] <- "red" 
x$color[x$cyl==6] <- "blue" 
x$color[x$cyl==8] <- "darkgreen"  
dotchart(x$mpg,labels=row.names(x),cex=.7,groups= x$cyl, 
     main="Gas Milage for Car Models\ngrouped by cylinder", 
     xlab="Miles Per Gallon", gcolor="black", color=x$color) 

enter image description here

+0

一个侧面说明,你可能只是做'C( “红”, “蓝”,” darkgreen“)[x $ cyl]''color ='参数到'dotchart' – thelatemail

+0

@thelatemail,好点,赞同,我实际上玩的是不同的参数,比如线条大小,颜色等等。 –

回答

3

一个快速收拾rownames的是,你可以做以下的列。

我们使用factor()的美学色彩,使之成为独立/ 当刻面,以达致这看你需要为scalespace指定"free_y"

基地

library(tidyverse) 
mtcars2 = rownames_to_column(mtcars, "car") 
ggplot(mtcars2, aes(x = mpg, y = factor(car), color = factor(cyl))) + 
    geom_point(shape = 1) + 
    facet_grid(cyl ~ ., scales = "free_y", space = "free_y") + 
    theme_bw() + 
    theme(panel.grid = element_blank(), 
     panel.grid.major.y = element_line(size=.1, color="grey90"), 
     legend.position = "none") + 
    ggtitle("Gas Milage for Car Models\ngrouped by cylinder") + 
    xlab("Miles Per Gallon") + 
    ylab("") 

enter image description here


添加文本

ggplot(mtcars2, aes(x = mpg, y = factor(car), color = factor(cyl))) + 
    geom_point(shape = 1) + 
    geom_text(aes(label = mpg), colour = "grey40", size = 3, hjust = -0.3) + 
    facet_grid(cyl ~ ., scales = "free_y", space = "free_y") + 
    theme_bw() + 
    theme(panel.grid = element_blank(), 
     panel.grid.major.y = element_line(size=.1, color="grey90"), 
     legend.position = "none") + 
    ggtitle("Gas Milage for Car Models\ngrouped by cylinder") + 
    xlab("Miles Per Gallon") + 
    ylab("") 

enter image description here

你或许可以使用geom_label而不是geom_text在这里效果很好。

+0

我该如何添加每个点顶部的实际mpg值。现在它只是一个圆圈。在网点上显示实际值将会很好。 –

+0

ive为每个点旁边的文本添加了一个版本,因此每个点都可见 – zacdav

4

修改@ zacdav的回答略有使用forcats订购各组内的点:

library(tidyverse) 
library(forcats) 
mtcars2 = rownames_to_column(mtcars, "car") %>% 
    mutate(car_ordered = fct_reorder2(car, cyl, mpg, .desc = FALSE)) 

ggplot(mtcars2, aes(x = mpg, y = car_ordered, color = factor(cyl))) + 
    geom_point(shape = 1) + 
    geom_text(aes(label = mpg), colour = "grey40", size = 3, hjust = -0.3) + 
    facet_grid(cyl ~ ., scales = "free_y", space = "free_y") + 
    theme_bw() + 
    theme(panel.grid = element_blank(), 
      panel.grid.major.y = element_line(size=.1, color="grey90"), 
      legend.position = "none") + 
    ggtitle("Gas Milage for Car Models\ngrouped by cylinder") + 
    xlab("Miles Per Gallon") + 
    ylab("") 

enter image description here

相关问题