如何在R中使用图例来获取以下数据
ID Gender Age Site Times
1 Male 24 Facebook 10
2 Female 24 Linkedin 10
3 Male 24 Twitter 10
4 Female 24 Myspace 10
5 Male 24 Facebook 10
6 Female 24 linkedin 10
7 Male 24 Facebook 10
阅读我用过的CSV
pd.readcsv <- read.csv(file = "snsite.csv")
设计我用过的饼图
pie(pd.freq[order(pd.freq,decreasing = T)],
col = c("Blue","Green","Yellow","Brown","Green"),
border = NA, main = "Site Usage")
现在要在右上角或左上角显示图例,如何从csv文件中以不同的形式读取一个列(站点)值并将其存储在变量中并在图例函数中使用它?
答案 0 :(得分:0)
我不知道你从哪里获得pd.freq对象,但假设你试图得到一个饼图,显示每个站点访问每个站点多少次,那么这应该可以解决问题。
# Read dataframe, I would recommend including the stringsAsFactors = FALSE argument to your read.csv command
pd.readcsv <- read.table(text = "ID Gender Age Site Times
1 Male 24 Facebook 10
2 Female 24 Linkedin 10
3 Male 24 Twitter 10
4 Female 24 Myspace 10
5 Male 24 Facebook 10
6 Female 24 linkedin 10
7 Male 24 Facebook 10",
header = TRUE, stringsAsFactors = FALSE)
# Convert sites to lowercase for proper aggregation
pd.readcsv$Site <- sapply(pd.readcsv$Site, tolower)
# Get vector of unique site names
sites <- unique(pd.readcsv$Site)
# Create aggregate dataframe with total times per site
pd.SumSiteTimes <- aggregate(Times~Site, sum, data = pd.readcsv)
# Create vector for colors
colors <- c("Blue","Green","Yellow","Brown","Green")
# Create pie chart
pie(pd.SumSiteTimes$Times[order(pd.SumSiteTimes$Times,decreasing = T)],
col = colors,
border = NA,
main = "Site Usage")
# Add legend to the plot
legend("topright", sites, cex = .8, fill = colors)