首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ggplot版本的dotplot

ggplot版本的dotplot
EN

Stack Overflow用户
提问于 2017-09-14 04:24:05
回答 2查看 424关注 0票数 1

想知道如何使用ggplot或巧妙的库函数来绘制这个点图。同时将mpg值标记在单个点上。

代码语言:javascript
复制
# 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)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-09-14 04:41:40

通过快速清除行名作为列,您可以执行以下操作。

我们使用factor()作为颜色的美学,这样它就变得离散了/当看到这个外观时,您需要为scalespace指定"free_y"

基座

代码语言:javascript
复制
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("")

添加文本

代码语言:javascript
复制
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("")

您可能可以使用geom_label,但geom_text在这里工作得很好。

票数 5
EN

Stack Overflow用户

发布于 2017-09-14 04:49:37

修改@zacdav的答案,使用forcats对每组中的点数排序

代码语言:javascript
复制
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("")

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46210504

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档