Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R geom_文本中每个标签的字体大小不同_R_Ggplot2 - Fatal编程技术网

R geom_文本中每个标签的字体大小不同

R geom_文本中每个标签的字体大小不同,r,ggplot2,R,Ggplot2,我用ggplot2制作了一个条形图。我想使用geom_text将标签添加到每个条中,以便标签的文本大小与标签相对应。为此,我使用了以下代码: a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i))) p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + geom_bar(stat="identity",position="d

我用
ggplot2
制作了一个条形图。我想使用
geom_text
将标签添加到每个条中,以便标签的文本大小与标签相对应。为此,我使用了以下代码:

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))
p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
      geom_bar(stat="identity",position="dodge") + 
      geom_text(data = a, aes(label = mpg, size = mpg), 
                position = position_dodge(width=0.9))
a将大小设置为
sort(a$mpg)
就可以了

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
    geom_bar(stat="identity",position="dodge") + 
    geom_text(data = a, aes(label = mpg), 
              position = position_dodge(width=0.9), size = sort(a$mpg))

p您可以更改
scale\u size
的范围

例如,如果希望缩放大小的范围从字体大小15到字体大小28:

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity", position="dodge") + 
  geom_text(data = a, aes(label = mpg, size = mpg), 
            position = position_dodge(width=0.9)) +
  scale_size(range = c(15, 28), guide = F) #legend hidden

在您的回答中,20和21之间的文本大小似乎是互换的。可能是因为数据的顺序是
15 21 20 28
?@SBista,确实正确,
a$mpg
的顺序是
15 21 20 28
,因此更新了ans
ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity", position="dodge") + 
  geom_text(data = a, aes(label = mpg, size = mpg), 
            position = position_dodge(width=0.9)) +
  scale_size(range = c(15, 28), guide = F) #legend hidden