TransWikia.com

How to define pgfkeys for pgfplots axis environments?

TeX - LaTeX Asked on October 4, 2021

I am trying to write a function that allows to add additional environments to a pgfplots axes environment.

I have come up with the following example:

documentclass{standalone}
usepackage{pgfkeys}
usepackage{pgfplots}
pgfplotsset{compat=1.17}
pgfkeys{
  /myPlot/.is family, /myPlot/.cd,
  default/.style={
    axis={},
    plot={},
  },
  axisCommands/.style={},
  axis/.style={axisCommands/.style={#1}},
  plotCommands/.style={},
  plot/.style={plotCommands/.style={#1}},
}
% 
newcommandExample[1][]{
    pgfkeys{/myPlot, default, #1}
    begin{tikzpicture}[]
    begin{axis}[/myPlot/axisCommands/.try]
    addplot[domain=0:1,samples=10, /myPlot/plotCommands/.try] {x};
    end{axis}
    end{tikzpicture}
}
% 
begin{document}
Example[axis={/pgfplots/xlabel=x, /pgfplots/ylabel=y}, plot={blue}]{}
end{document}

As you can see, I am able to define ‘axis’ and ‘plot’ as keys. However, the axis environments must have `/pgfplots/’ in front of them. I would like to set them in the newcommand environment, but so far I have not been able to do so. When I remove it, it shows the error message

I don’t know the key ‘/tikz/xlabel’ to which you passed ‘x’

Does anyone have an explanation and/or solution for this problem?

One Answer

To get rid of usages axis={/pgfplots/xlabel=x, /pgfplots/ylabel=y}, you only need to change the default path to /pgfplots/ inside

axis/.style={axisCommands/.style={#1}},
% and
plot/.style={plotCommands/.style={#1}},

A tricky detail:

  • addplot[] ...; resets default style of a plotting, hence the markers (filled circles in blue) are not drawn and the blue color is reset to black. To append styles to the default one, addplot+ is used in the following example.

A full example:

documentclass{standalone}
usepackage{pgfplots}
pgfplotsset{compat=1.17}

pgfkeys{
  /myPlot/.is family, /myPlot/.cd,
  default/.style={
    axis={},
    plot={},
  },
  axisCommands/.style={},
  axis/.style={axisCommands/.style={/pgfplots/.cd, #1}},
  plotCommands/.style={},
  plot/.style={plotCommands/.style={/pgfplots/.cd, #1}},
}

newcommandExample[1][]{
  pgfkeys{/myPlot, default, #1}
  begin{tikzpicture}[]
    begin{axis}[/myPlot/axisCommands/.try]
      addplot+[domain=0:1, samples=10, /myPlot/plotCommands/.try] {x};
    end{axis}
  end{tikzpicture}
}
 
begin{document}
Example[%
  axis={xlabel=x, ylabel=y},
  % comment the following line to restore to default style (in blue)
  plot={orange, mark options={orange}}
]{}
end{document}

enter image description here

Correct answer by muzimuzhi Z on October 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP