0

I am having some trouble plotting on Tikz. I want to generate a plot like this,

enter image description here

but instead, my Tikz generates this.

enter image description here

How can I improve my Tikz?

\documentclass[10pt,a4paper]{article}
\usepackage[utf8]{inputenc} % International characters
\usepackage[T1]{fontenc} % Font encoding for international characters
% \usepackage{fouriernc} % Use the New Century Schoolbook font
\usepackage{lmodern} % Use Latin Modern font
% \usepackage{libertine} % Use LLibertine font
% \usepackage{libertinust1math}% Use LLibertine math font
\usepackage{geometry} % Setting page geometry (margins)
\usepackage{blindtext} % Lorem ipsum
\usepackage{textcomp} % For the trademark symbol
\usepackage{booktabs} % Allows the use of \toprule, \midrule and \bottomrule in tables for horizontal lines
\usepackage{siunitx} % Allows for properly formatted numbers with \num{number}, units with \si{unit} and both with \si{number}{unit}
\usepackage{microtype} % A few refinements to typography that are hardly noticeable
\usepackage[normalem]{ulem} %Strikethrough text
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{calc}

%Tables \usepackage{float} % image positioning \usepackage{multirow} \usepackage{array} \usepackage{tabu} \usepackage{tikz} \usepackage{longtable} \usepackage{caption} \usepackage{tabularx}

%Itemize \usepackage{etoolbox,refcount} \usepackage{multicol} \usepackage{setspace}

%Fonts \usepackage{titlesec} \titleformat{\section}{\normalfont\fontsize{11pt}{11pt}\selectfont\bfseries}{\thesection}{1em}{} \titleformat*{\subsection}{\normalsize\bfseries}

%Chemistry \usepackage[version=3]{mhchem} \usepackage[separate-uncertainty]{siunitx} \DeclareSIUnit\molar{\mole\per\cubic\deci\metre} \DeclareSIUnit\Molar{\textsc{M}}

%Page Number \usepackage{fancyhdr} \pagestyle{fancy} \fancyhf{} % clear all header and footer fields \fancyfoot[R]{\thepage} % page number on right bottom

%Graphs \usepackage{pgfplots} %Graph \pgfplotsset{compat=1.5} \usepackage{graphicx} \usepackage{adjustbox}

\usepackage{amsmath} % amsmath も必要 \usepackage{mathtools} \mathtoolsset{showonlyrefs}

% Package must come last \usepackage[bookmarks=true]{hyperref} % Hyperrefs for bookmarks \hypersetup{ colorlinks=true, citecolor=black, linkcolor=blue, filecolor=magenta,
urlcolor=blue, } \usepackage{bookmark} % Adds metadata to PDF for bookmarking

% Package settings & macros

\renewcommand{\contentsname}{Contents} % Contents heading

\urldef{\usePercentage}\url{%} % Using the percent symbol in documents: \usePercentage

\usepackage[citestyle=authoryear,bibstyle=mla,sorting=nty]{biblatex} % bibliography \usepackage{url} \usepackage{appendix}

\renewcommand{\nameyeardelim}{\addcomma\addspace} \addbibresource{references.bib} \urlstyle{same} \renewcommand*{\bibfont}{\scriptsize}

% Document Settings \geometry{margin=1in} \setlength{\parskip}{1ex} \setlength{\parindent}{0pt} \renewcommand{\headrulewidth}{0pt}

\newlength{\conditionwd} \newenvironment{conditions}[1][where:] {% #1\tabularx{\textwidth-\widthof{#1}}[t]{ >{$}l<{$} @{${}={}$} X@{} }% } {\endtabularx\[\belowdisplayskip]} \newcounter{countitems} \newcounter{nextitemizecount} \newcommand{\setupcountitems}{% \stepcounter{nextitemizecount}% \setcounter{countitems}{0}% \preto\item{\stepcounter{countitems}}% } \makeatletter \newcommand{\computecountitems}{% \edef@currentlabel{\number\c@countitems}% \label{countitems@\number\numexpr\value{nextitemizecount}-1\relax}% } \newcommand{\nextitemizecount}{% \getrefnumber{countitems@\number\c@nextitemizecount}% } \newcommand{\previtemizecount}{% \getrefnumber{countitems@\number\numexpr\value{nextitemizecount}-1\relax}% } \makeatother
\newenvironment{AutoMultiColItemize}{% \ifnumcomp{\nextitemizecount}{>}{3}{\begin{multicols}{2}}{}% \setupcountitems\begin{itemize}}% {\end{itemize}% \unskip\computecountitems\ifnumcomp{\previtemizecount}{>}{3}{\end{multicols}}{}}

\begin{document}

\begin{figure}[H] \caption{the effect of increasing \ce{CuSO4} concentrations on voltage produced}\label{fg:plot} \begin{center} \begin{adjustbox}{max width = 200mm} \begin{tikzpicture} \pgfplotsset{width=5in, height=4in} \begin{axis}[ axis lines = left, xlabel = concentration of \ce{CuSO4} (\si{mol.dm^{-3}}), ylabel = mean voltage produced (\si{V}), xmin=-3, xmax=8, ymin=1.550, ymax=1.950, xtick={-3.0, -2.0, -1.0, 0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8}, ytick={1.550, 1.600, 1.650, 1.700, 1.750, 1.800, 1.850, 1.900}, legend pos=north west, ] \addplot [ domain=-2.302585093:6.907755279, samples=1000, color=blue, ] {-0.0301x+1.7967}; \addlegendentry {$-0.0301x+1.7967$} \addplot[ only marks, color=blue, mark=, error bars/.cd, y dir=both, y explicit, x dir=both, x explicit, ] coordinates { (6.907755279, 1.586) +- (0, 0) (4.605170186, 1.662) +- (0, 0) (2.302585093, 1.732) +- (0, 0) (0, 1.789) +- (0, 0) (-2.302585093, 1.869) +- (0, 0) }; \end{axis} \end{tikzpicture} \end{adjustbox} \end{center} \end{figure}

\end{document}

  • Can you please add the few missing lines of code, so we can copy and compile? BTW, the preamble holds relevant information, too. Thanks – MS-SPO Jun 03 '23 at 05:52
  • Is is a tikz plot (as in the title) or a pgfplots as in the code added? – Raffaele Santoro Jun 03 '23 at 06:34
  • Thanks for the comments. I have updated my codes (sorry it's really messy). – observer_meow Jun 03 '23 at 11:02
  • Thanks. It should be minimal, i.e. provide what's needed and discarding all the other noise (which only your final document needs). // Kindly see my answer at https://tex.stackexchange.com/a/687558/245790 . – MS-SPO Jun 03 '23 at 12:43
  • @observer_meow, it is while when you got two good answers. Now is time that you choose one which you most liked and accept it. – Zarko Nov 04 '23 at 12:50

2 Answers2

2

Here's a way to do it, at least in most parts.

To start with: if you want to look like Excel, use Excel, e.g. by saving your diagram as bitmap and include it, e.g. via package graphicx.

I reduced your code to the basics needed here: all other code may be relevant to your document, but is irrelevant here. (So next time please boil down the problem by discarding, as I did, before posting.)

As far as I read it, pgfplot is intended to create drawings used in scientific publications and similar. So shifting the y-axis is simply not provided for this reason. (If it would, it could obscure the values put on the axes.) However, a common solution you'll find elsewhere on this site and in the manual is drawing some extra ticks, pretending being some extra axis.

Some things I did to your code besides deleting:

  • using \documentclass[10pt,border=3mm,tikz]{standalone} makes creating and focusing on tikz-diagrams easier
  • to follow the x-axis in your example, I reduced xtick to xtick={-2.0, 0, 2.0, 4.0, 6.0, 8},
  • I neglected the \ce{} macro: it's easier for you to find out, which code is required to make that one work

Also I put these statements to draw both major grids and put some minor grid for the y-axis by adopting a solution to Minor grid in pgfplot not showing when specifying ticks manualy:

        grid=major,
        yminorgrids,
        minor y tick num =5,
        minor grid style={draw=gray!20,line width=1pt},% adjust as needed
        extra x ticks={0},% page 99
        extra x tick style={grid style={black}},% adjust as needed

BTW, you can, but you don't need to use coordinates. Just look for scatter plot and table data in the manual.

result

\documentclass[10pt,border=3mm,tikz]{standalone}
\usepackage{siunitx} % Allows for properly formatted numbers with 
%%Chemistry
%\usepackage[version=3]{mhchem}
%\usepackage[separate-uncertainty]{siunitx}
%\DeclareSIUnit\molar{\mole\per\cubic\deci\metre}
%\DeclareSIUnit\Molar{\textsc{M}}

%Graphs \usepackage{pgfplots} %Graph \pgfplotsset{compat=1.5}

\begin{document}

\begin{tikzpicture} \pgfplotsset{width=5in, height=4in} \begin{axis}[ axis lines = left, xlabel = concentration of CuSO4 (\si{mol.dm^{-3}}), ylabel = mean voltage produced (\si{V}), xmin=-3, xmax=8, ymin=1.550, ymax=1.950, % xtick={-3.0, -2.0, -1.0, 0, 1.0, 2.0, 3.0, 4.0, 5.0, % 6.0, 7.0, 8}, xtick={-2.0, 0, 2.0, 4.0, 6.0, 8}, ytick={1.550, 1.600, 1.650, 1.700, 1.750, 1.800, 1.850, 1.900}, legend pos=north west, grid=major, yminorgrids, minor y tick num =5, minor grid style={draw=gray!20,line width=1pt}, extra x ticks={0},% page 99 extra x tick style={grid style={black}}, ] \addplot [ domain=-2.302585093:6.907755279, samples=1000, color=blue, ] {-0.0301*x+1.7967};

\addlegendentry {$-0.0301x+1.7967$}

\addplot[
    only marks,
    color=blue,
    mark=*,
    error bars/.cd,
    y dir=both, y explicit,
    x dir=both, x explicit,
]
coordinates {
    (6.907755279, 1.586)    +- (0, 0)
    (4.605170186, 1.662)    +- (0, 0)
    (2.302585093, 1.732)    +- (0, 0)
    (0, 1.789)              +- (0, 0)
    (-2.302585093, 1.869)   +- (0, 0)
};

\end{axis} \end{tikzpicture}

\end{document}

MS-SPO
  • 11,519
  • 1
    Thank you so much as well! I've never thought of Tikz graph with the design you've proposed! – observer_meow Jun 04 '23 at 09:43
  • Fine :) We are all learning here. (I suppose you mean tikz in the documentclass statement. If so, that makes creating and inspecting drawings easier. Later you can include it more easily into your documents. See package graphicx for details.) – MS-SPO Jun 04 '23 at 10:06
2
  • Please, next time provide MWE (Minimal Working Example), in which preamble are loaded only to your problem relevant package and contain only to problem relevant definitions (see, how are construct MWEs' in received answers).
  • Some packages are ancient. I strongly encourage to upgrade your LaTeX installation to recent one (pgfplots to 1.18, mchem to version 4, etc.).
  • My answer is small variation of nice MS-SPO answer (different are used diagram axis, removed tick positions, etc.):
  • MWE reproduce the first showed image in your question:
\documentclass[border=3mm]{standalone}
\usepackage{siunitx}
\usepackage[version=4]{mhchem}  % <---

%Graphs \usepackage{pgfplots} %Graph \pgfplotsset{compat=1.18} % <---

\begin{document} \begin{tikzpicture} \pgfplotsset{width=5in, height=4in} \begin{axis}[ axis lines = middle, title= Chart title, xlabel = concentration of \ce{CuSO4} (\si{mol.dm^{-3}}), xlabel style = {anchor=north east, yshift=-3ex}, ylabel = mean voltage produced (\si{V}), ylabel style = {xshift=-3cm, rotate=90, anchor=south east}, xmin=-3, xmax=8, ymin=1.55, ymax=1.9, legend pos=north east, ymajorgrids, yminorgrids, minor y tick num =4, minor grid style={draw=gray!20,very thin}, xtick distance = 2, tick label style = {font=\footnotesize, fill=white}, extra x ticks={0},% page 99 extra x tick style={grid style={black}}, ] \addplot [domain=-2.4:7,samples=2,color=blue]{-0.0301x+1.7967}; \addlegendentry {$-0.0301x+1.7967$} \addplot[only marks, mark=,color=blue, %error bars/.cd, % not neede if "+- (0, 0.)" %y dir=both, y explicit, %x dir=both, x explicit ] coordinates { (6.907755279, 1.586) %+- (0, 0.01) (4.605170186, 1.662) %+- (0, 0.01) (2.302585093, 1.732) %+- (0, 0.01) (0, 1.789) %+- (0, 0.01) (-2.302585093, 1.869) %+- (0, 0.01) }; \end{axis} \end{tikzpicture} \end{document}

enter image description here

Edit: Corrected misspelled MS-SPO name. Sorry for error, but he si really PRO!

Zarko
  • 296,517