2013-05-16 48 views
4

一个复杂的气泡图我有一个数据集是这样的(简化的用于说明目的):如何创建中的R

zz <- textConnection("Company Market.Cap Institutions.Own Price.Earnings Industry 
ExxonMobil 405.69 50% 9.3 Energy 
Citigroup 156.23 67% 18.45 Banking 
Pfizer 212.51 73% 20.91 Pharma 
JPMorgan 193.1 75% 9.12 Banking 
") 
Companies <- read.table(zz, header= TRUE) 
close(zz) 

我想创建气泡图(当然,像气泡图)具有以下属性:

  • 每个气泡是一个公司,随着气泡绑市场帽的尺寸,
  • 气泡绑行业的颜色,
  • 与x轴有两个类别,Industries.Own和Price.Earnings,
  • ,y轴是1-10的比例,每个公司的值被归一化为该比例。 (我当然可以做外R上的正常化,但我相信R采用的是可能的。)

需要明确的是,每家公司都会出现在结果中的每一列,例如埃克森美孚将接近两者的底部Institutions.Own专栏和Price.Earnings专栏;理想情况下,公司的名称会出现在其两个气泡中或旁边。

回答

6

我认为这涉及到你的所有观点。请注意 - 您的Institutions.Own是因为%而被作为因素读入的......我只是简单地将其删除以便于时间...您需要在某处解决该问题。一旦完成,我会使用ggplot并相应地映射您的不同美学。如果需要,你可以摆弄轴标题等。

#Requisite packages 
library(ggplot2) 
library(reshape2) 
#Define function, adjust this as necessary 
rescaler <- function(x) 10 * (x-min(x))/(max(x)-min(x)) 
#Rescale your two variables 
Companies$Inst.Scales <- with(Companies, rescaler(Institutions.Own)) 
Companies$Price.Scales <- with(Companies, rescaler(Price.Earnings)) 
#Melt into long format 
Companies.m <- melt(Companies, measure.vars = c("Inst.Scales", "Price.Scales")) 
#Plotting code 
ggplot(Companies.m, aes(x = variable, y = value, label = Company)) + 
    geom_point(aes(size = Market.Cap, colour = Industry)) + 
    geom_text(hjust = 1, size = 3) + 
    scale_size(range = c(4,8)) + 
    theme_bw() 

结果:

enter image description here