代码之家  ›  专栏  ›  技术社区  ›  Mauro

R:Labels-()命令在尝试将X轴标签设置到直方图时不起作用。

  •  1
  • Mauro  · 技术社区  · 6 年前

    简化和尝试使我的错误可重复,我的代码如下,它生成一个直方图,然后设置X轴和Y轴:

        set.seed(100)
    
        dist <- data.frame(rnorm(200, sd = 300000))
    
        histogram <- hist(dist$rnorm.200., col = "orange", breaks = 100, main = "VaR distribution", xlab = "P&L", axes = FALSE)
    
        axis(1, at = seq(min(dist), max(dist), length = 7))
        labels(formatC(seq(min(dist$rnorm.200.)/1000000, max(dist$rnorm.200.)/1000000, length = 7), format = "d", digits = 0))
    
        axis(2, at = seq(from = 0, to = max(histogram$counts), by = 5))
        labels(formatC(seq(from = 0, to = max(histogram$counts), by = 5), format = "d"))
    

    在轴Y上设置标签的命令,但是X轴标签命令没有,如下所示:

    axis(1, at = seq(min(dist), max(dist), length = 7))
        labels(formatC(seq(min(dist$rnorm.200.)/1000000, max(dist$rnorm.200.)/1000000, length = 7), format = "d", digits = 0))
    

    而不是得到7个值的序列 dist$norm.200. 除以1000000,不加小数,我得到的默认值设置为 histogram() 功能。

    版本:无论是Y轴标签命令,也不工作,我感谢它在我原来的代码,因为它匹配因果关系。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Lennyy    6 年前

    你应该用 labels 作为 axis() 函数,而不是单独的函数。像这样的:

    set.seed(100)
    
    dist <- data.frame(rnorm(200, sd = 300000))
    
    histogram <- hist(dist$rnorm.200., col = "orange", breaks = 100, main = "VaR distribution", xlab = "P&L", axes = FALSE)
    
    axis(1, at = seq(min(dist), max(dist), length = 7), labels = formatC(seq(min(dist$rnorm.200.)/1000000, max(dist$rnorm.200.)/1000000, length = 7), format = "d", digits = 0))
    
    axis(2, at = seq(from = 0, to = max(histogram$counts), by = 5), labels = (formatC(seq(from = 0, to = max(histogram$counts), by = 5), format = "d")))
    

    formatC(seq(min(dist$rnorm.200.)/1000000, max(dist$rnorm.200.)/1000000, length = 7), format = "d", digits = 0) 只返回零,所以您可能想对这些标签实际应该是什么给予更多关注。(或许可以除以100000?)

        2
  •  1
  •   Wimpel    6 年前

    这里是一个ggplot2方法。我发现代码更容易阅读,更容易维护。

    set.seed(100)
    dist <- data.frame(rnorm(200, sd = 300000))
    
    library(ggplot2)
    ggplot(dist, aes( x = dist[,1] ) ) + 
      geom_histogram( bins = 100, color = "black", fill = "orange" ) +
      scale_x_continuous( labels = function(x){x / 100000} ) + 
      labs( title = "VaR distribution",
            x = "P&L",
            y = "Frequency" )
    

    enter image description here