【问题标题】:Unwanted irregular interval between y-axis ticks, ggplot2 bar charty轴刻度之间不需要的不规则间隔,ggplot2条形图
【发布时间】:2016-12-12 16:40:48
【问题描述】:

我正在尝试使用 http://www.cookbook-r.com/Graphs/Bar_and_line_graphs_(ggplot2)/ 之后的 ggplot2 在 r 中创建一个简单的条形图 当我在 y 轴下方运行代码时,不会以连续比例绘制。相反,间隔是不规则的,每个刻度设置等于我输入的值。如何将比例更改为从 0% 到 -70% 的常规 10% 间隔?

# Replicate dataset
seg=c(rep("City",2),rep("Supermini",2),rep("Small family",2),
rep("Large family",2),rep("MPV",2),
rep("Compact executive",2),rep("Executive",2),
rep("Sports",2),rep("SUV",2),rep("Luxury",2))

leg=rep(c("Cost","Mass"),10)

val=c(-0.26,-0.14, -0.34, -0.09, -0.21, -0.13, -0.09, -0.03, -0.22, -0.04,
-0.58, -0.24, -0.47,-0.44,-0.42,-0.14,-0.61,-0.39,-0.43,-0.03)

bardata=as.data.frame(cbind(seg,leg,val))

# Create bar chart
library(ggplot2)

ggplot(bardata, aes(factor(seg), val, fill = leg)) + 
  geom_bar(stat="identity", position = "dodge")+
  scale_fill_manual(values=c("deepskyblue4","deepskyblue2"))+
  labs(fill=NULL)+
  xlab(NULL)+
  ylab("Percentage change relative to base case")

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    使用cbind 生成一个矩阵,它强制所有列采用相同的class。相反,使用以下代码生成您的 data.frame:

    bardata <- data.frame(seg,leg,val)
    

    它会保留数据的不同类别。当ggplotval 列绘制为一个因子时,它无法知道它实际上应该是数字。

    【讨论】:

    • 非常感谢 - 希望我早点发布这个问题!
    猜你喜欢
    • 2019-09-06
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 2012-04-24
    • 2017-09-23
    相关资源
    最近更新 更多