在ggplot2条形图中勾选标签

Gre*_*ton 10 plot r ggplot2

我有一个简单的数据帧,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
Run Code Online (Sandbox Code Playgroud)

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

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

当我尝试修改值标签时出现问题.如果我这样做,我最终会在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"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

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)) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

hrb*_*str 17

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

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)
Run Code Online (Sandbox Code Playgroud)

(根据评论者的说法,你可以而且应该只使用没有列的名字$而且我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)
Run Code Online (Sandbox Code Playgroud)

正常工作(factor()x让你使用scale_x_discrete)