【问题标题】:Tick labels in ggplot2 bar graphggplot2条形图中的刻度标签
【发布时间】:2014-03-09 21:33:15
【问题描述】:

我有一个简单的数据框,by_day,我想绘制出来:

 X weekday         variable value
0       0 Number_of_tweets  5820
1       1 Number_of_tweets  6965
2       2 Number_of_tweets  7415
3       3 Number_of_tweets  6800
4       4 Number_of_tweets  5819
5       5 Number_of_tweets  1753
6       6 Number_of_tweets  1137

我可以毫无问题地获得基本情节。

daily_plot <- ggplot(data=by_day, aes(x=by_day$weekday, y=by_day$value)) + 
  geom_bar(stat = "identity") 

当我尝试修改值标签时出现问题。如果我这样做,我最终会在 x 轴的右侧有额外的空间:

daily_plot + 
  scale_x_discrete("Day of the Week", breaks = c("0","1","2","3","4","5","6"), labels=c("Mon","Tues","Wed","Th","Fri","Sat","Sun"))

如果我这样做,那么问题是条形和新标签偏移

daily_plot + 
  scale_x_discrete("Day of the Week", breaks = c("0","1","2","3","4","5","6"),    labels=c("Mon","Tues","Wed","Th","Fri","Sat","Sun"), limits=c("0","1","2","3","4","5","6")) + 
  theme(axis.title.x = element_text(vjust=-0.5), axis.title.y=element_text(vjust=0.1)) 

我花了一些时间查看 ggplot2 文档以及 StackOverflow,但找不到相同的问题。任何帮助将不胜感激。

【问题讨论】:

    标签: r plot ggplot2


    【解决方案1】:

    尝试使用连续比例尺(因为您没有使用因子):

    by_day <- data.frame(
      X=0:6,
      weekday=0:6,
      variable="Number_of_tweets",
      value=c(5820,6965,7415,6800,5819,1753,1137))
    
    print(by_day)
    
    ##   X weekday         variable value
    ## 1 0       0 Number_of_tweets  5820
    ## 2 1       1 Number_of_tweets  6965
    ## 3 2       2 Number_of_tweets  7415
    ## 4 3       3 Number_of_tweets  6800
    ## 5 4       4 Number_of_tweets  5819
    ## 6 5       5 Number_of_tweets  1753
    ## 7 6       6 Number_of_tweets  1137
    
    daily_plot <- ggplot(data=by_day, aes(x=weekday, y=value))
    daily_plot <- daily_plot + geom_bar(stat = "identity") 
    daily_plot <- daily_plot + scale_x_continuous(breaks=0:6,
                                                  labels=c("Mon","Tue","Wed","Thu","Fri","Sat","Sun"))
    print(daily_plot)
    

    (对于每个评论者,您可以而且应该只使用不带$ 的列名,而我的group= 不是必需的[我的习惯力量])。

    还有:

    daily_plot <- ggplot(data=by_day, aes(x=factor(weekday), y=value))
    daily_plot <- daily_plot + geom_bar(stat = "identity") 
    daily_plot <- daily_plot + scale_x_discrete(breaks=0:6,
                                                labels=c("Mon","Tue","Wed","Thu","Fri","Sat","Sun"))
    print(daily_plot)
    

    工作正常(factor() for x 允许您使用 scale_x_discrete

    【讨论】:

    • 如果您 (1) 删除不必要的 group 美学映射,(2) 删除 $aes 内的使用,并附上说明说明这应该永远完成,并且 (3) 请注意,如果您将 weekday 转换为数据框本身中的一个因子/字符,scale_x_discrete 将正常工作。
    • 适合我剪切和粘贴一些原始ggplot 代码。给我一秒钟... :-) 完成。
    • 不用担心...我的意思是,我可以自己编辑它,但是这么多的编辑会有点粗鲁。 :)
    • 知识转移绝不是粗鲁的。也更新了情节帖子-factor() 示例。谢谢。
    • 谢谢 hrbmastr 和 joran!我的身材修好了,学到了一些东西——非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2017-10-30
    • 2013-07-23
    • 2018-11-13
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多