如何调整ggplot代码使绘制的图形符合预期样式?
调整ggplot代码匹配预期图形样式
我尝试用ggplot绘制图形,代码如下:
ggplot(data.frame(x=c(0,25)),aes(x=x))+ stat_function(fun=function(x){(18-6*x)/4},aes(color="Function 1"))+ stat_function(fun=function(x){(24-4*x)/3},aes(color="Function 2"))+ stat_function(fun=function(x){(20-10*x)/2},aes(color="Function 3"))+ theme_bw()+ scale_color_discrete(name="Function")+ geom_polygon(data=data.frame(x=c(0,3,Inf,3),y=c(4.5,0,Inf,Inf)), aes(x=x,y=y,fill="Constraint 1"),inherit.aes=F,alpha=0.4)+ scale_fill_discrete(name="Constraint Set")+ scale_y_continuous(limits=c(0,10.5))+ scale_x_continuous(limits=c(0,7))
当前图形:仅显示Constraint 1的填充区域,三条函数线超出合理范围(存在y为负的部分),且缺少另外两个约束的填充区域。
预期图形:三条函数线仅显示y≥0的部分,同时包含三个约束对应的填充区域(各函数线与坐标轴围成的三角形区域)。
解决方案
1. 修正函数线的显示范围
给每个stat_function添加xlim参数,限制函数仅在y≥0的x区间内绘制:
stat_function(fun=function(x){(18-6*x)/4}, aes(color="Function 1"), xlim = c(0, 3))+ stat_function(fun=function(x){(24-4*x)/3}, aes(color="Function 2"), xlim = c(0, 6))+ stat_function(fun=function(x){(20-10*x)/2}, aes(color="Function 3"), xlim = c(0, 2))
2. 重构约束填充区域数据
每个约束的填充区域是函数线、x轴、y轴围成的三角形,将三个约束的顶点数据合并为一个数据框:
constraint_data <- rbind( data.frame(x=c(0,0,3), y=c(0,4.5,0), constraint="Constraint 1"), data.frame(x=c(0,0,6), y=c(0,8,0), constraint="Constraint 2"), data.frame(x=c(0,0,2), y=c(0,10,0), constraint="Constraint 3") )
3. 完整调整后的代码
library(ggplot2) # 构造约束填充区域的多边形数据 constraint_data <- rbind( data.frame(x=c(0,0,3), y=c(0,4.5,0), constraint="Constraint 1"), data.frame(x=c(0,0,6), y=c(0,8,0), constraint="Constraint 2"), data.frame(x=c(0,0,2), y=c(0,10,0), constraint="Constraint 3") ) ggplot(data.frame(x=c(0,7)), aes(x=x))+ # 绘制三条函数线,限制x范围避免负y值 stat_function(fun=function(x){(18-6*x)/4}, aes(color="Function 1"), xlim = c(0, 3))+ stat_function(fun=function(x){(24-4*x)/3}, aes(color="Function 2"), xlim = c(0, 6))+ stat_function(fun=function(x){(20-10*x)/2}, aes(color="Function 3"), xlim = c(0, 2))+ # 绘制所有约束的填充区域 geom_polygon(data=constraint_data, aes(x=x,y=y,fill=constraint), alpha=0.4, inherit.aes=F)+ # 主题与刻度配置 theme_bw()+ scale_color_discrete(name="Function")+ scale_fill_discrete(name="Constraint Set")+ scale_y_continuous(limits=c(0,10.5))+ scale_x_continuous(limits=c(0,7))
调整说明
- 限制函数线的x区间,确保只显示y≥0的部分,匹配预期图形中函数线的长度
- 替换错误的多边形数据,用三角形顶点构造符合要求的约束填充区域
- 合并约束数据,简化代码结构的同时保证三个约束区域都能正确显示
内容的提问来源于stack exchange,提问作者Restu
相关产品推荐
相关产品推荐

