簡體   English   中英

制作帶有正值和負值的條形圖

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

有這樣的數據框:

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

如何制作一個情節,將正面的名字放在一邊,而將負面的名字放在另一邊?

這樣的情節

您可以使用以下代碼

  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")

在此處輸入圖片說明

更新

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")

在此處輸入圖片說明

您可以根據頻率對因素進行排序:

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