ggplot繪圖系統精華帖~

2021-02-21 數據小魔方

本文轉載自公眾號:每天都有進步


ggplot2 Pk 基本繪圖

基本圖形

# 房價數據

housing <- read.csv("dataSets/landdata-states.csv")

head(housing[1:5])

#日期數據轉換成數值數據

housing <- read.csv("dataSets/landdata-states.csv")

housing$Year <- as.numeric(substr(housing$Date, 1, 4))

housing$Qrtr <- as.numeric(substr(housing$Date, 5, 5))

housing$Date <- housing$Year + housing$Qrtr/4

#基本繪圖

hist(housing$Home.Value)

#ggplot2 繪圖

library(ggplot2)

ggplot(housing, aes(x = Home.Value)) +

  geom_histogram()

複雜繪圖

#基本繪圖

plot(Home.Value ~ Date,

     data=subset(housing, State == "MA"))

points(Home.Value ~ Date, col="red",

       data=subset(housing, State == "TX"))

legend(1975, 3e5,

       c("MA", "TX"), title="State",

       col=c("black", "red"),

       pch=c(1, 1))

#ggplot2 繪圖

ggplot(subset(housing, State %in% c("MA", "TX")),

       aes(x=Date,

           y=Home.Value,

           color=State))+

  geom_point()

ggplot2 之美#散點圖

hp2001Q1 <- subset(housing, Date == 2001.25) 

ggplot(hp2001Q1,

       aes(y = Structure.Cost, x = Land.Value)) +

  geom_point()

#坐標取對數

ggplot(hp2001Q1,

       aes(y = Structure.Cost, x = log(Land.Value))) +

  geom_point()

#線性擬合

hp2001Q1$pred.SC <- predict(lm(Structure.Cost ~ log(Land.Value), data = hp2001Q1))

p1 <- ggplot(hp2001Q1, aes(x = log(Land.Value), y = Structure.Cost))

p1 + geom_point(aes(color = Home.Value)) +

  geom_line(aes(y = pred.SC))

#平滑預測

p1 +

  geom_point(aes(color = Home.Value)) +

  geom_smooth()

#為數據點添加標籤

p1 + 

  geom_point() + 

  geom_text(aes(label=State), size = 3)

#辨識標記數據點

library("ggrepel")

p1 + 

  geom_point() + 

  geom_text_repel(aes(label=State), size = 3)

#為數據點添加顏色

p1 +

  geom_point(aes(size = 2),

             color="red") 

#顏色映射給房屋價格,形狀映射給地區

p1 +

  geom_point(aes(color=Home.Value, shape = region))

#經濟數據

dat <- read.csv("dataSets/EconomistData.csv")

head(dat)

#繪製CPI和HPI(人類發展指數)散點圖

ggplot(dat, aes(x = CPI, y = HDI, size = HDI.Rank)) + geom_point()

#改變點顏色

ggplot(dat, aes(x = CPI, y = HDI)) +

  geom_point(color = "blue")

#點顏色映射給地區

ggplot(dat, aes(x = CPI, y = HDI)) +

  geom_point(aes(color = Region))

#改變x , y 軸及圖例名

ggplot(dat, aes(x = CPI, y = HDI, color = Region)) +

geom_point() +

scale_x_continuous(name = "Corruption Perception Index") +

scale_y_continuous(name = "Human Development Index") +

scale_color_discrete(name = "Region of the world")

#自定義顏色為各地區

ggplot(dat, aes(x = CPI, y = HDI, color = Region)) +

geom_point() +

scale_x_continuous(name = "Corruption Perception Index") +

scale_y_continuous(name = "Human Development Index") +

  scale_color_manual(name = "Region of the world",

                     values = c("#24576D",

                                "#099DD7",

                                "#28AADC",

                                "#248E84",

                                "#F2583F",

                                "#96503F"))

#改變點的大小

ggplot(dat, aes(x = CPI, y = HDI)) +

  geom_point(aes(color = Region), size = 2)

#點的大小映射給人類發展指數排名

ggplot(dat, aes(x = CPI, y = HDI)) +

geom_point(aes(color = Region, size =  HDI.Rank))

#擬合線的美化

ggplot(dat, aes(x = CPI, y = HDI)) +

  geom_point() +

  geom_smooth()

#線性擬合

ggplot(dat, aes(x = CPI, y = HDI)) +

  geom_point() +

  geom_smooth(method = "lm")

#不繪製擬合區間

ggplot(dat, aes(x = CPI, y = HDI)) +

  geom_point() +

  geom_line(stat = "smooth", method = "loess")

#增加擬合的平滑性

ggplot(dat, aes(x = CPI, y = HDI)) +

  geom_point() +

  geom_smooth(span = .4)

ggplot2 之 統計轉化

p2 <- ggplot(housing, aes(x = Home.Value))

p2 + geom_histogram()

#頻度陰影圖

p2 + geom_histogram(stat = "bin", binwidth=4000)

#用aggregate 對數據重組

housing.sum <- aggregate(housing["Home.Value"], housing["State"], FUN=mean)

rbind(head(housing.sum), tail(housing.sum))

#繪製條形圖

ggplot(housing.sum, aes(x=State, y=Home.Value)) + 

  geom_bar(stat="identity")

 ggplot2 之 尺度轉化

#美國各州房價指數圖

p3 <- ggplot(housing,

             aes(x = State,

                 y = Home.Price.Index)) + 

        theme(legend.position="top",

              axis.text=element_text(size = 6))

(p4 <- p3 + geom_point(aes(color = Date),

                       alpha = 0.5,

                       size = 1.5,

                       position = position_jitter(width = 0.25, height = 0)))

#改變x軸標籤和圖例標籤

p4 + scale_x_discrete(name="State Abbreviation") +

  scale_color_continuous(name="",

                         breaks = c(1976, 1994, 2013),

                         labels = c("'76", "'94", "'13"))

#改變點顏色用一種漸變到另一種顏色

p4 +

  scale_x_discrete(name="State Abbreviation") +

  scale_color_continuous(name="",

                         breaks = c(1976, 1994, 2013),

                         labels = c("'76", "'94", "'13"),

                         low = "blue", high = "red")

#使用muted柔和色

library("scales")

p4 +

  scale_color_continuous(name="",

                         breaks = c(1976, 1994, 2013),

                         labels = c("'76", "'94", "'13"),

                         low = muted("blue"), high = muted("red"))

p4 +

  scale_color_gradient2(name="",

                        breaks = c(1976, 1994, 2013),

                        labels = c("'76", "'94", "'13"),

                        low = muted("blue"),

                        high = muted("red"),

                        mid = "gray60",

                        midpoint = 1994)

ggplot 之 分面

#用不同顏色表示每個州房價隨時間增長曲線

p5 <- ggplot(housing, aes(x = Date, y = Home.Value))

p5 + geom_line(aes(color = State))

#用分面的形式表示每個州房價隨時間增長曲線

(p5 <- p5 + geom_line() +

   facet_wrap(~State, ncol = 10))

#修改分面主題

#黑線

p5 + theme_linedraw()

#亮線

p5 + theme_light()

# 更炫主題一

p5 + theme_minimal() +

  theme(text = element_text(color = "turquoise"))

#更炫主題 二

library(scales)

theme_new <- theme_bw() +

  theme(plot.background = element_rect(size = 1, color = "blue", fill = "black"),

        text=element_text(size = 12, color = "ivory"),

        axis.text.y = element_text(colour = "purple"),

        axis.text.x = element_text(colour = "red"),

        panel.background = element_rect(fill = "pink"),

        strip.background = element_rect(fill = muted("orange")))

p5 + theme_new

分別繪製曲線

#方法一

housing.byyear <- aggregate(cbind(Home.Value, Land.Value) ~ Date, data = housing, mean)

ggplot(housing.byyear,

       aes(x=Date)) +

  geom_line(aes(y=Home.Value), color="red") +

  geom_line(aes(y=Land.Value), color="blue")

#方法二

library(tidyr)

home.land.byyear <- gather(housing.byyear,

                           value = "value",

                           key = "type",

                           Home.Value, Land.Value)

ggplot(home.land.byyear,

       aes(x=Date,

           y=value,

           color=type)) +

  geom_line()

有趣的點符

#25個點符

df2 <- data.frame(x = 1:5 , y = 1:25, z = 1:25)

s <- ggplot(df2, aes(x = x, y = y))

s + geom_point(aes(shape = z), size = 4) + scale_shape_identity()

綜合案例分析之經濟學人圖片

library("ggrepel")

library(grid)

dat <- read.csv("dataSets/EconomistData.csv")

pointsToLabel <- c("Russia", "Venezuela", "Iraq", "Myanmar", "Sudan",

                   "Afghanistan", "Congo", "Greece","Argentina","Brazil",

                   "India", "Italy", "China", "South Africa", "Spane",

                   "Botswana", "Cape Verde", "Bhutan", "Rwanda", "France", 

                   "United States", "Germany", "Britain", "Barbados", 

                   "Norway", "Japan","New Zealand", "Singapore")

dat$Region <- factor(dat$Region,

                     levels = c("EU W. Europe",

                                "Americas",

                                "Asia Pacific",

                                "East EU Cemt Asia",

                                "MENA",

                                "SSA"),

                     labels = c("OECD",

                                "Americas",

                                "Asia &\nOceania",

                                "Central &\nEastern Europe",

                                "Middle East &\nnorth Africa",

                                "Sub-Saharan\nAfrica"))

mR2 <- summary(lm(HDI ~ log(CPI), data = dat))$r.squared

ggplot(dat, aes(x = CPI, y = HDI, color = Region))+

  geom_smooth(aes(group = 1),

              method = "lm",

              formula = y ~ log(x),

              se = FALSE,

              color = "red") +

  geom_point(shape = 1, size = 2.5, stroke = 1.25)+

  geom_text_repel(aes(label = Country),

                  color = "gray20",

                  data = subset(dat, Country %in% pointsToLabel),

                  force = 10)+

  scale_x_continuous(name = "Corruption Perceptions Index, 2011 (10=least corrupt)",

                     limits = c(.9, 10.5),

                     breaks = 1:10) +

  scale_y_continuous(name = "Human Development Index, 2011 (1=Best)",

                     limits = c(0.2, 1.0),

                     breaks = seq(0.2, 1.0, by = 0.1)) +

  scale_color_manual(name = "",

                     values = c("#24576D",

                                "#099DD7",

                                "#28AADC",

                                "#248E84",

                                "#F2583F",

                                "#96503F")) +

  ggtitle("Corruption and Human development")+

  theme_minimal() + 

  theme(text = element_text(color = "gray20"),

        legend.position = c("top"), 

        legend.direction = "horizontal",

        legend.justification = 0.1,

        legend.text = element_text(size = 11, color = "gray10"),

        axis.text = element_text(face = "italic"),

        axis.title.x = element_text(vjust = -1),

        axis.title.y = element_text(vjust = 2),

        axis.ticks.y = element_blank(), 

        axis.line = element_line(color = "gray40", size = 0.5),

        axis.line.y = element_blank(),

        panel.grid.major = element_line(color = "gray50", size = 0.5),

        panel.grid.major.x = element_blank()

  )

grid.text("Sources: Transparency International; UN Human Development Report",

          x = .02, y = .03,

          just = "left",

          draw = TRUE)

grid.segments(x0 = 0.81, x1 = 0.825,

              y0 = 0.90, y1 = 0.90,

              gp = gpar(col = "red"),

              draw = TRUE)

grid.text(paste0("R² = ",

                 as.integer(mR2*100),

                 "%"),

          x = 0.835, y = 0.90,

          gp = gpar(col = "gray20"),

          draw = TRUE,

          just = "left")

歡迎大家關注原文作者微信公眾號:

相關焦點

  • ggplot2包的繪圖邏輯簡介
    在R語言裡,談及繪圖,ggplot2是最出名的繪圖包之一,作為一個繪圖神器,它提供了許許多多的功能給用戶使用,僅用短短幾行代碼,一幅幅高端大氣的圖像便躍然紙上,這可能就是ggplot2包的魅力所在。我們用相同的數據,通過plot函數跟ggplot函數分別繪製散點圖來簡單理解一下兩者的差異:library("ggplot2")    #加載安裝好的ggplot2包plot(iris$Sepal.Length, iris$Sepal.Width) #plot繪圖ggplot(data = iris,aes(x = Sepal.Length
  • R語言繪圖之ggplot2
    那麼今天我們就為大家介紹一下目前在R語言中流行的繪圖包ggplot2。1. ggplot2的安裝:install.packages("ggplot2")。2. ggplot2的繪圖原理: ggplot2的核心理念是將繪圖與數據分離,數據相關的繪圖與數據無關的繪圖分離,並按圖層作圖。
  • Python數據可視化--在Python中調用ggplot進行繪圖
    如果想要在Python中調用ggplot,我們該怎麼辦呢?本文提供了兩種不同的方式:在Python中調用R:直接使用R語言的ggplot2調用Python版的ggplot:ggplot與plotnine(推薦)1. 在Python中調用Rrpy2包可以讓Python和R共同工作。
  • R語言 ggplot2 繪圖入門,看完你就理解ggplot2的繪圖邏輯了
    R語言最擅長繪圖。R語言最擅長的繪圖包是ggplot2,由於很多朋友沒有接觸過ggplot2,必須要對其語言方式有個初步的認識。
  • 高階可視化繪圖系統:ggplot2入門
    數據(Data)和映射(Mapping)2、幾何對象(Geometric)3、標度(Scale):fill、color、shape4、統計變換(Stat)5、坐標系統(Coordinante)6、分面(Facet)7、主題(Theme)8、實例:0-1分色附:ggplot2函數速查表
  • ggplot2|詳解八大基本繪圖要素
    此外, 圖形中還可能包含數據的統計變換(statistical transformation, 縮寫為stats), 最後繪製在某個特定的坐標系(coordinate system,  縮寫為coord)中, 而分面(facet, 指將繪圖窗口劃分為若干個子窗口)則可以用來生成數據中不同子集的圖形。"
  • ggplot2|theme主題設置,詳解繪圖優化-「精雕細琢」
    學習了ggplot2的基本繪圖元素ggplot2|詳解八大基本繪圖要素,可以初步繪製出需要展示的圖形
  • R繪圖之ggplot2—添加注釋
    傳遞給圖層的其他基礎參數,如size, colour, alpha, fill, fontface等na.rm刪除缺失值時是否提醒annotate 函數的參數較為簡單,大多是layer()中的基礎參數第二部分: 添加文本添加文本類幾何對象library(ggplot2)library(ggsci)library
  • R語言 高階可視化繪圖系統:ggplot2入門 | 第8講
    數據(Data)和映射(Mapping)2、幾何對象(Geometric)3、標度(Scale):fill、color、shape4、統計變換(Stat)5、坐標系統(Coordinante)6、分面(Facet)7、主題(Theme)8、實例:0-1分色附:ggplot2函數速查表
  • 乾貨 | 繪圖的基本元素(ggplot2實現)
    用R進行數據可視化可以有多種選擇,你可以用R的基礎繪圖系統,也可以使用其他的包,例如ggplot2、Lattice等等。作為一個懶人,最開始使用基礎的R繪圖系統時感覺非常蹩腳,後來開始嘗試ggplot2便一直用到現在。在ggplot2的github上有一個頁面列出了為什麼使用ggplot2的理由,我個人將這些理由總結為四點,以下將分別說明。
  • R語言可視化——ggplot圖表中的線條
    R語言中ggplot函數系統中涉及到線條的地方有很多,最常見的場景就是我們做geom_line()(折線圖)、geom_path()(路徑圖),以及圖表的繪圖區(panel)、圖表區、網格系統(grid)中所涉及到的線條。今天以一個折線圖為例,簡要說明ggplot函數中關於線條的主要參數及其效果。
  • ggplot2|繪製GO富集柱形圖
    本文利用R語言的ggplot2包,從頭帶您繪製可發表級別的GO富集分析結果圖。利用各種生信工具得到富集分析結果,數據列可能不一致,但關鍵幾列都有。3.3 調整label長度後繪圖GO_term_order=factor(as.integer(rownames(data)),labels=labels)COLS <- c("#66C3A5", "#8DA1CB", "#FD8D62")ggplot(data=data, aes(x=GO_term_order,y=Num_of_symbols_in_list_in_GO
  • 微課|ggplot2: 折線圖
    使用ggplot2繪製折線圖.折線圖整體美化.繪製平滑折線圖.繪製多變量折線圖.
  • Python語言plotnine VS R語言ggplot2
    相對於R中的基礎可視化包,是基於圖形語法的繪圖包,一經提出就迅速受到廣大R語言使用者的喜愛。ggplot2包利用圖層疊加的繪圖方式,往圖像上不斷的添加圖形元素、注釋、統計結果等內容。plotnine庫可以看作是在Python中對ggplot2包的一種實現,方便Python對數據可視化的應用。本文章會分別介紹在R和Python中,如何使用相關的庫進行數據可視化分析。
  • R語言統計與繪圖:怎麼加載Windows系統字體到圖形上?
    前言作圖的時候常出現一個問題,我把windows系統字體「Times New Roman」指定為圖形裡的字體,雖然在RStudio圖形窗口會顯示指定字體,但是在保存為PDF時出現問題,出現字體類別錯誤,指定字體無法顯示。
  • 如何在Python裡用ggplot2繪圖
    ggplot2的繪圖方法不僅確保每個繪圖包含特定的基本元素,而且在很大程度上簡化了代碼的可讀性。但是,如果您經常使用Python,那麼實現圖形語法將非常具有挑戰性,因為在流行的繪圖庫(如matplotlib或seaborn)中缺少標準化語法。如果您仍然希望使用圖形語法,那麼Python包plotnine為您提供了另一種選擇。
  • R語言——ggplot2的繪圖邏輯
    在R語言裡,談及繪圖,ggplot2是最出名的繪圖包之一,作為一個繪圖神器,它提供了許許多多的功能給用戶使用,僅用短短幾行代碼,一幅幅高端大氣的圖像便躍然紙上,這可能就是ggplot2包的魅力所在。我們用相同的數據,通過plot函數跟ggplot函數分別繪製散點圖來簡單理解一下兩者的差異:library("ggplot2")    #加載安裝好的ggplot2包plot(iris$Sepal.Length, iris$Sepal.Width) #plot繪圖ggplot(data = iris,aes(x = Sepal.Length
  • 「繪圖之王」爭霸賽——Excel才是繪圖王道
    Python為了進一步提升自己的繪圖能力,還開發了Prettyplotlib和Seaborn兩個繪圖包。Seaborn的繪圖風格和R語言的ggplot2很類似。圖1.2.1(b) 是使用Matlab 2013a經調整和修飾展現的散點圖,效果還不錯。Matlab 2014b 推出了全新的Matlab圖形系統。全新的默認顏色、字體和樣式便於數據解釋。
  • 基於ggplot2包繪製SCI學術箱線圖的保姆級教程
    install.packages("ggplot2")library(ggplot2)plot_pir <- ggplot(data = box_data,aes(x = Type, y = AOD_550nm))+  geom_boxplot(aes(fill=Type))+  labs(caption
  • 超棒教程:如何用ggplot2繪製漂亮的統計圖形
    目  錄本期內容將會介紹 ggplot2 繪圖語法的基礎,以及如何調整圖形坐標軸的內容和外觀、修改圖形標題等內容。ggplot2是一個基於圖形語法(The Grammar of Graphics)的繪圖系統。簡單來說,你只需要提供數據(data),並告訴ggplot2如何將變量映射到美學(aesthetics),使用什麼圖形元素(geoms),然後它將會處理剩餘的細節。什麼是圖形語法?