讀取檔案

library(datasets)
library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(tidyr)
dta <- datasets::USPersonalExpenditure
colnames(dta) <- c("year1940","year1945","year1950","year1955","year1960")

新增category變項

dta <- as.data.frame(dta)

dat <- stack(round(log10(dta), 2))

class(dat)
## [1] "data.frame"
dat$category <- c("Food_Tobacco","Household_Operation","Medical_Health","Personal_Care","Private_Education")
head(dat)
##   values      ind            category
## 1   1.35 year1940        Food_Tobacco
## 2   1.02 year1940 Household_Operation
## 3   0.55 year1940      Medical_Health
## 4   0.02 year1940       Personal_Care
## 5  -0.47 year1940   Private_Education
## 6   1.65 year1945        Food_Tobacco

繪圖

p0 <- ggplot(dat) +
  aes(x=values, y=category) +
  geom_point(size=rel(3)) +
  facet_grid(. ~ ind) +
  geom_segment(aes(xend=dat$values, yend=dat$category, x=mean(dat$values))) + 
  geom_vline(aes(xintercept=mean(values)))

p0
## Warning: Use of `dat$values` is discouraged. Use `values` instead.

## Warning: Use of `dat$values` is discouraged. Use `values` instead.
## Warning: Use of `dat$category` is discouraged. Use `category` instead.