R的Python等效条形图

时间:2015-01-09 10:25:09

标签: python r

以下代码来自Udacity的“统计简介”

#Write a line of code to produce a barchart of Weight by groups of Height 
#using the barchart function

from plotting import *

Height=[65.78, 71.52, 69.4, 68.22, 67.79, 68.7, 69.8, 70.01, 67.9, 66.78,
66.49, 67.62, 68.3, 67.12, 68.28, 71.09, 66.46, 68.65, 71.23, 67.13, 67.83, 
68.88, 63.48, 68.42, 67.63, 67.21, 70.84, 67.49, 66.53, 65.44, 69.52, 65.81, 
67.82, 70.6, 71.8, 69.21, 66.8, 67.66, 67.81, 64.05, 68.57, 65.18, 69.66, 67.97, 
65.98, 68.67, 66.88, 67.7, 69.82, 69.09]

Weight=[112.99, 136.49, 153.03, 142.34, 144.3, 123.3, 141.49, 136.46, 
112.37, 120.67, 127.45, 114.14, 125.61, 122.46, 116.09, 140.0, 129.5, 142.97, 
137.9, 124.04, 141.28, 143.54, 97.9, 129.5, 141.85, 129.72, 142.42, 131.55, 
108.33, 113.89, 103.3, 120.75, 125.79, 136.22, 140.1, 128.75, 141.8, 121.23, 
131.35, 106.71, 124.36, 124.86, 139.67, 137.37, 106.45, 128.76, 145.68, 116.82, 
143.62, 134.93]

barchart(Height, Weight)

以下是输出

enter image description here

执行此代码会返回一个条形图,显示高度与重量的线性关系。

R中有什么等价的吗?

感谢。

1 个答案:

答案 0 :(得分:2)

我宁愿做一个简单的散点图:

Height=c(65.78, 71.52, 69.4, 68.22, 67.79, 68.7, 69.8, 70.01, 67.9, 66.78,
        66.49, 67.62, 68.3, 67.12, 68.28, 71.09, 66.46, 68.65, 71.23, 67.13, 67.83, 
        68.88, 63.48, 68.42, 67.63, 67.21, 70.84, 67.49, 66.53, 65.44, 69.52, 65.81, 
        67.82, 70.6, 71.8, 69.21, 66.8, 67.66, 67.81, 64.05, 68.57, 65.18, 69.66, 67.97, 
        65.98, 68.67, 66.88, 67.7, 69.82, 69.09)

Weight=c(112.99, 136.49, 153.03, 142.34, 144.3, 123.3, 141.49, 136.46, 
        112.37, 120.67, 127.45, 114.14, 125.61, 122.46, 116.09, 140.0, 129.5, 142.97, 
        137.9, 124.04, 141.28, 143.54, 97.9, 129.5, 141.85, 129.72, 142.42, 131.55, 
        108.33, 113.89, 103.3, 120.75, 125.79, 136.22, 140.1, 128.75, 141.8, 121.23, 
        131.35, 106.71, 124.36, 124.86, 139.67, 137.37, 106.45, 128.76, 145.68, 116.82, 
        143.62, 134.93)

plot(Height, Weight)

enter image description here

但你可以使用选项type来使用其他类型的情节。例如:

plot(Height, Weight, type="h")

编辑:通过示例图,问题可能更清楚。

评论:我认为通过这样做有很多浪费的信息,并且它没有很好地说明两个变量之间的线性链接...

这是一个命题:我假设有序因子是基于身高的,并且它用于聚合权重(通过计算身高属于某个仓的个体权重的平均值)。

  1. 首先从变量Height创建有序因子:

    f <- cut(Height, 5, ordered_result = TRUE)
    
  2. 根据此有序因子,汇总权重:

    y <- tapply(Weight, f, mean)
    
  3. 情节:

    barplot(y, col="steelblue", border=NA, xlab="Height", ylab="Weight" )
    
  4. enter image description here