【问题标题】:How to combine a plot and legend?如何结合情节和传说?
【发布时间】:2012-02-20 18:14:32
【问题描述】:

我正在尝试将图例附加到 R 中的情节。 我尝试了以下代码(取自http://www.harding.edu/fmccown/r/

# Define cars vector with 5 values
cars <- c(1, 3, 6, 4, 9)

# Define some colors ideal for black & white print
colors <- c("white","grey70","grey90","grey50","black")

# Calculate the percentage for each day, rounded to one 
# decimal place
car_labels <- round(cars/sum(cars) * 100, 1)

# Concatenate a '%' char after each value
car_labels <- paste(car_labels, "%", sep="")

# Create a pie chart with defined heading and custom colors
# and labels
pie(cars, main="Cars", col=colors, labels=car_labels,
   cex=0.8)

# Create a legend at the right   
legend(1.5, 0.5, c("Mon","Tue","Wed","Thu","Fri"), cex=0.8, 
   fill=colors)

但是,这并不能很好地工作。在 pie(cars, main="Cars", col=colors, labels=car_labels,cex=0.8) 行之后,显示的图没有图例:-) ......我在网上看到的每一个例子似乎在绘图函数之后都有legend函数所以看起来很诡异.............

当我尝试执行图例函数时,我得到了

legend(1.5, 0.5, c("Mon","Tue","Wed","Thu","Fri"), cex=0.8, +填充=颜色) strwidth 中的错误(图例,单位 =“用户”,cex = cex): plot.new 还没有被调用

【问题讨论】:

    标签: r plot legend


    【解决方案1】:

    您不在坐标系中。试试这个

    # Create a legend at the right   
    legend("topleft", c("Mon","Tue","Wed","Thu","Fri"), cex=0.8, fill=colors)
    

    生成下面的图表:

    请参阅legend 的帮助页面以了解不同的放置选项。

    【讨论】:

      【解决方案2】:

      我认为1.5, 0.5 的位置将其从页面上移开。试试

      legend("right", c("Mon","Tue","Wed","Thu","Fri"), cex=0.8, fill=colors)
      

      pie 函数之后,它没有图例; legend 函数将图例添加到当前绘图中。

      PS。您也可以考虑其他类型的地块。饼图因在视觉上具有误导性而臭名昭著。

      【讨论】:

        猜你喜欢
        • 2022-08-14
        • 2021-08-10
        • 2018-07-08
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        • 2011-09-08
        • 1970-01-01
        相关资源
        最近更新 更多