在R中绘制三个以上的变量

时间:2017-11-08 20:37:29

标签: r ggplot2

首先在这里查询!希望得到一个好的回应。我想在R中绘制下表。

dfr <- data.frame (
Member = c("Old", "New", "Old", "New", "Old", "New", "Old", "New"), 
Years = c(2005,2005, 2006,2006,2013,2013,2014,2014), 
Trust = c(42.3, 56.70, 45.30, 61.40, 26.80, 45.50, 33.5, 50.60), # these are percentages 
mistrust = c(45.50, 28.50, 42, 25.20, 62.70, 42.90, 54.20, 34.20))

您也知道,该成员意味着新老欧盟成员国,而我有兴趣了解每一组新老欧盟成员国在欧盟的信任程度。

这里的问题是我想绘制所有四个变量,图表显示不同成员(新旧)的信任和/或不信任在四个不同年份之间的变化情况。

我希望我的意思是有道理的!

由于

1 个答案:

答案 0 :(得分:0)

How about this - using dplyr and ggplot2?

dfr <- data.frame (
  Member = c("Old", "New", "Old", "New", "Old", "New", "Old", "New"), 
  Years = c(2005,2005, 2006,2006,2013,2013,2014,2014), 
  Trust = c(42.3, 56.70, 45.30, 61.40, 26.80, 45.50, 33.5, 50.60), # these are percentages 
  mistrust = c(45.50, 28.50, 42, 25.20, 62.70, 42.90, 54.20, 34.20))

Your data are in wide format, where column names give information. We need it in long format, for which we use 'gather'.

library(tidyverse)

dfr.g <- dfr %>%
  gather(key=Type, value=Score, Trust,mistrust,-Member,-Years)

Then we make a parallel plot in ggplot2, as shown.

ggplot(dfr.g,
       aes(x=Years, y=Score, colour=Type,
           group=interaction(Member,Type), fill=Member)) +
  geom_line() +
  geom_point(size=2, shape=21, colour="grey50") +
  scale_fill_manual(values=c("black","white")) +
  scale_x_continuous(breaks=seq(from=2005,to=2014,by=2))

Derived from this answer - How to plot parallel coordinates with multiple categorical variables in R