简体   繁体   English

制作带有正值和负值的条形图

[英]Make a bar plot with positive and negative values

Having a dataframe like this:有这样的数据框:

data.frame(names = c("yahoo", "google", "amazon", "aliexpress"), frq = c(3,1,-4,-1))

How is it possible to make a plot to have the positive names into one side and the negative from the other?如何制作一个情节,将正面的名字放在一边,而将负面的名字放在另一边?

Something like this plot这样的情节

You can use the following code您可以使用以下代码

  library(ggplot2)
  df <- data.frame(names = c("yahoo", "google", "amazon", "aliexpress"), frq = c(3,1,-4,-1))
        
  ggplot(df, aes(x=names, y=frq, fill=names)) + 
  geom_bar(position=position_dodge(), stat="identity") + 
  scale_x_discrete(limits = df$names)+ theme(legend.position="none")+
  xlab("Names") +
  ylab("Frequency")

在此处输入图片说明

Update更新

ggplot(df, aes(x=names, y=frq)) + 
  geom_bar(aes(fill = frq < 0), stat = "identity") + 
  scale_fill_manual(guide = FALSE, breaks = c(TRUE, FALSE), values=c("Green", "red")) + 
  scale_x_discrete(limits = df$names)+ theme(legend.position="none")+
  xlab("Names") +
  ylab("Frequency")

在此处输入图片说明

You can just order the factors according to frequency:您可以根据频率对因素进行排序:

library(ggplot2)
h <- data.frame(names = c("yahoo", "google", "amazon", "aliexpress"), frq = c(3,1,-4,-1))

h$names <- factor(h$names, levels = h$names[order(h$frq)])
h$positive <- ifelse(h$frq>0, 1, 0)

ggplot(h, aes(names, frq, fill=positive)) + geom_bar( stat = "identity")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM