knitr::opts_chunk$set(warning = FALSE, message = FALSE)
这类图片一开始是从棒棒糖1图开始接触的2,今天看到的两个变形,一起都学习一下。
library(tidyverse)
p1 <- mtcars %>%
rownames_to_column() %>%
ggplot(aes(x = reorder(rowname,mpg), y = mpg)) +
# geom_point()
geom_point(shape = 21, size = 3, col = 'black', fill = '#FC4E07') +
coord_flip()
p1
#FC4E07
这个是颜色编号,网上可以搜索一下。shape = 21
报错 Error: A continuous variable can not be mapped to shape
. 不要把shape
放入aes
中。棒棒糖图主要参考#301 Custom lollipop chart – The R graph Gallery,因为这里的代码有问题3。
# Library
library(tidyverse)
# Create data
data <-
data.frame(x=LETTERS[1:26], y=abs(rnorm(26))) %>%
mutate(x = reorder(x,y))
# 1 - Custom markers (left)
# note: shape = integer between 0 and 25
# note: stroke exists only for shapes between 1 and 24
ggplot(data, aes(x=reorder(x,y), y=y)) +
geom_segment( aes(x=x, xend=x, y=0, yend=y)) +
geom_point( size=5, color="red", fill=alpha("orange", 0.3), alpha=0.7, shape=21, stroke=2) +
coord_flip()
# 2 - Custom stems (right)
# note: size is the width in mm
# note: style can be in: "blank", "solid", "dashed", "dotted", "dotdash", "longdash","twodash"
ggplot(data, aes(x=x, y=y)) +
geom_segment( aes(x=x, xend=x, y=0, yend=y) , size=1, color="blue", linetype="dotted" ) +
geom_point() +
coord_flip()
就是在Cleveland’sDot Plots基础上加一个group对比。
# Library
library(tidyverse)
# Create data
value1=abs(rnorm(26))*2
data=data.frame(x=LETTERS[1:26], value1=value1, value2=value1+1+rnorm(26, sd=1) ) %>%
mutate( x =reorder(x,value2))
# Reorder data using average?
data = data %>% rowwise() %>% mutate( mymean = mean(c(value1,value2) )) %>% arrange(mymean) %>% mutate(x=factor(x, x))
# plot
ggplot(data) +
geom_segment( aes(x=x, xend=x, y=value1, yend=value2), color="grey") +
geom_point( aes(x=x, y=value1), color=rgb(0.2,0.7,0.1,0.5), size=3 ) +
geom_point( aes(x=x, y=value2), color=rgb(0.7,0.2,0.1,0.5), size=3 ) +
coord_flip()
# With a bit more style
ggplot(data) +
geom_segment( aes(x=x, xend=x, y=value1, yend=value2), color="grey") +
geom_point( aes(x=x, y=value1), color=rgb(0.2,0.7,0.1,0.5), size=3 ) +
geom_point( aes(x=x, y=value2), color=rgb(0.7,0.2,0.1,0.5), size=3 ) +
coord_flip()+
theme_light() +
theme(
legend.position = "none",
panel.border = element_blank(),
) +
xlab("") +
ylab("Value of Y")
棒棒糖图是二维图,一个numeric、一个factor变量,或者一个factor变量和求count。↩