显示第二组/类别的图边上的条

时间:2018-11-22 11:53:38

标签: r ggplot2

我创建了一个绘图,该可视化代码按照我的意图可视化数据:

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        UserDefaults.standard.set(true, forKey: "VC1") //Key changes based on the current viewController used in example (VC1, VC2, VC3)
    }
    override func viewWillAppear(_ animated: Bool) {
        if self.isAllVistied() {
            view.backgroundColor = .green
        }
    }
}

enter image description here

我现在想在侧面添加一个栏来解释类别列中定义的分组。也应显示此类别的图例或标签。 enter image description here

1 个答案:

答案 0 :(得分:2)

首先生成类别向量

# list the categories by their freqencies
cgy <- as.data.frame(table(data$category), stringsAsFactors=FALSE)
# convert the values so that a "0" category finds place
# the "0" category is needed because groups starting at "1"
cgy$Freq <- cgy$Freq/10*9
cgy <- rbind(c(0, 10), cgy)  # bind a "0" category 
# get the desired vector
cgy.v <- unlist(sapply(1:nrow(cgy), function(x) rep(cgy[x, 1], cgy[x, 2])))
rm(cgy)  # clean up

您的情节

p <- ggplot() +
  theme(legend.position="none", 
        panel.grid.major=element_blank(), 
        panel.grid.minor=element_blank(),
        panel.background=element_blank(), 
        axis.title.y=element_blank(), 
        axis.ticks.y=element_blank(),
        axis.text.y=element_blank()) +
  geom_path(data=data, mapping=aes(x=x, y=y, col= group, alpha=0.5)) +
  geom_point(data=data, mapping=aes(x=x, y=y, col= group))

添加

p + geom_bar(data=data, aes(0, y = as.integer(category)/22),
             fill = factor(sort(cgy.v), 
                           labels=(c("white", "blue", "orange", "yellow", "green"))),
             stat = "identity") +
# the labels: 
geom_text(aes(x=0, 
              y=c(as.integer(table(cgy.v)))/10, 
              label=c("",sort(unique(cgy.v))[-1])), 
          size=4, 
          color="black", position=position_stack(vjust=.5))

屈服

enter image description here