如何在LaTeX pgfplots中消除数据末端的竖直线
解决pgfplots折线图2019处出现竖直线的问题
嗨,我明白你的问题了——那条突兀的竖直线是因为你用了\closedcycle命令导致的!让我给你解释清楚原因,再提供两种针对性的解决办法:
问题根源
\closedcycle的作用是自动闭合绘图路径,它会把最后一个数据点垂直连接到x轴(y=0),然后沿着x轴回到第一个数据点的x坐标对应的x轴位置,再连回第一个数据点。你的数据截止到2019年,所以它就在2019的位置画了一条竖线到x轴,这就是你看到的那条多余线条。
解决方法
方法1:不需要填充区域?直接删掉\closedcycle
如果你的需求只是绘制折线,不需要填充曲线下方的区域,那最简单的办法就是去掉\closedcycle命令。修改后的代码如下:
\documentclass[tikz, border=1mm]{standalone} \usepackage{pgfplots} % 别忘了显式加载pgfplots包,避免编译问题 \begin{document} \begin{tikzpicture} \begin{axis}[ width = 0.6\textwidth, xticklabel style= {/pgf/number format/1000 sep=,rotate=90,anchor=east}, xmin = 1995, xmax = 2020, ymin = 0, ymax = 1.2, xlabel = Year, ylabel style ={align=center}, ylabel = Specific energy consumption\\in kWh/pkm, yticklabels={, 0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2}] \addplot [] coordinates { (1995,1.102) (1996,1.067) (1997,1.048) (1998,0.939) (1999,0.905) (2000,0.901) (2001,0.924) (2002,0.944) (2003,0.906) (2004,0.9) (2005,0.901) (2006,0.89) (2007,0.854) (2008,0.829) (2009,0.813) (2010,0.839) (2011,0.846) (2012,0.831) (2013,0.772) (2014,0.768) (2015,0.785) (2016,0.794) (2017,0.765) (2018,0.755) (2019,0.768) }; % 移除\closedcycle,折线会正常截止到2019 \end{axis} \end{tikzpicture} \end{document}
方法2:需要填充曲线下方区域到2020?手动扩展路径
如果你想要填充曲线下方的区域,并且希望填充范围覆盖到xmax=2020的位置,可以在数据末尾添加(2020,0),再补充(1995,0)来闭合路径,这样就不会出现突兀的竖线,同时填充区域会延伸到2020的x轴位置。示例代码:
\documentclass[tikz, border=1mm]{standalone} \usepackage{pgfplots} \begin{document} \begin{tikzpicture} \begin{axis}[ width = 0.6\textwidth, xticklabel style= {/pgf/number format/1000 sep=,rotate=90,anchor=east}, xmin = 1995, xmax = 2020, ymin = 0, ymax = 1.2, xlabel = Year, ylabel style ={align=center}, ylabel = Specific energy consumption\\in kWh/pkm, yticklabels={, 0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2}] \addplot [fill=lightgray, draw=black] coordinates { (1995,1.102) (1996,1.067) (1997,1.048) (1998,0.939) (1999,0.905) (2000,0.901) (2001,0.924) (2002,0.944) (2003,0.906) (2004,0.9) (2005,0.901) (2006,0.89) (2007,0.854) (2008,0.829) (2009,0.813) (2010,0.839) (2011,0.846) (2012,0.831) (2013,0.772) (2014,0.768) (2015,0.785) (2016,0.794) (2017,0.765) (2018,0.755) (2019,0.768) (2020,0) % 延伸到xmax的x轴位置 (1995,0) % 回到起始点的x轴位置,闭合填充路径 }; \end{axis} \end{tikzpicture} \end{document}
内容的提问来源于stack exchange,提问作者Simon P
相关产品推荐
相关产品推荐

