막대 차트를 그리는 LaTeX 코드를 자동으로 생성하는 Python 스크립트가 있습니다. 생성된 코드의 예는 다음과 같습니다.
\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{width=7cm,compat=1.8}
\usepackage{pgfplotstable}
\renewcommand*{\familydefault}{\sfdefault}
\usepackage{sfmath}
\begin{document}
\begin{tikzpicture}
\centering
\begin{axis}[
ybar, axis on top,
title={Performance charts},
height=8cm, width=15.5cm,
bar width=1.5cm,
ymajorgrids, tick align=inside,
major grid style={draw=white},
enlarge y limits={value=.1,upper},
ymin=0, ymax=0.01,
axis x line*=bottom,
axis y line*=right,
y axis line style={opacity=0},
tickwidth=0pt,
enlarge x limits=true,
legend style={
at={(0.5,-0.2)},
anchor=north,
legend columns=-1,
/tikz/every even column/.append style={column sep=0.5cm}
},
ylabel={Time (seconds)},
symbolic x coords={
10,
20,
},
xtick=data,
nodes near coords={
\pgfmathprintnumber[precision=3]{\pgfplotspointmeta}
}
]
\addplot+[ybar, fill=blue!50] plot coordinates {
(10, 0.001223850250244141)
(20, 0.001497483253479004)
};
\addplot+[ybar, fill=blue!25] plot coordinates {
(10, 0.00045402050018310557)
(20, 0.001987481117248536)
};
\addplot+[ybar, fill=red!50] plot coordinates {
(10, 0.0008006999999999999)
(20, 0.0010588)
};
\addplot+[ybar, fill=red!25] plot coordinates {
(10, 0.0002661999999999997)
(20, 0.0012075)
};
\legend{Real Time (Loading), Real-Time (Querying), CPU Time (Loading), CPU Time (Querying)}
\end{axis}
\end{tikzpicture}
\end{document}
하지만 두 개의 실시간 막대가 서로 겹쳐지도록 하고 싶습니다. CPU 시간과 동일합니다. 따라서 x 좌표당 두 개의 막대가 있습니다. 이 라텍스 코드를 생성한 Python 코드는 다음과 같습니다.
def generate_latex_files(data, env_name, output_dir: Path) -> None:
for key, values in data.items():
if key[0] == env_name:
# Sort values by graph size
values.sort(key=lambda x: x[0])
# Calculate maximum value for ymax
max_value = max(sum(val['loading'] + val['querying']) for _, val in values) * 1.1
file_name = f'{key[1]}_{key[2]}.tex'
full_file_name = output_dir / env_name / file_name
full_file_name.parent.mkdir(exist_ok=True, parents=True)
with open(full_file_name, 'w') as f:
f.write('\\documentclass[border=10pt]{standalone}\n')
f.write('\\usepackage{pgfplots}\n')
f.write('\\pgfplotsset{width=7cm,compat=1.8}\n')
f.write('\\usepackage{pgfplotstable}\n')
f.write('\\renewcommand*{\\familydefault}{\\sfdefault}\n')
f.write('\\usepackage{sfmath}\n')
f.write('\\begin{document}\n')
f.write('\\begin{tikzpicture}\n')
f.write(' \\centering\n')
f.write(' \\begin{axis}[\n')
f.write(' ybar, axis on top,\n')
f.write(f' title={{Performance charts}},\n')
f.write(' height=8cm, width=15.5cm,\n')
f.write(' bar width=1.5cm,\n')
f.write(' ymajorgrids, tick align=inside,\n')
f.write(' major grid style={draw=white},\n')
f.write(' enlarge y limits={value=.1,upper},\n')
f.write(f' ymin=0, ymax={max_value:.2f},\n')
f.write(' axis x line*=bottom,\n')
f.write(' axis y line*=right,\n')
f.write(' y axis line style={opacity=0},\n')
f.write(' tickwidth=0pt,\n')
f.write(' enlarge x limits=true,\n')
f.write(' legend style={\n')
f.write(' at={(0.5,-0.2)},\n')
f.write(' anchor=north,\n')
f.write(' legend columns=-1,\n')
f.write(' /tikz/every even column/.append style={column sep=0.5cm}\n')
f.write(' },\n')
f.write(' ylabel={Time (seconds)},\n')
f.write(' symbolic x coords={\n')
for value in values:
f.write(f' {value[0]},\n')
f.write(' },\n')
f.write(' xtick=data,\n')
f.write(' nodes near coords={\n')
f.write(' \\pgfmathprintnumber[precision=3]{\\pgfplotspointmeta}\n')
f.write(' }\n')
f.write(' ]\n')
# Real time plots
f.write(' \\addplot+[ybar, fill=blue!50] plot coordinates {\n')
for value in values:
f.write(f' ({value[0]}, {value[1]["loading"][0]})\n')
f.write(' };\n')
f.write(' \\addplot+[ybar, fill=blue!25] plot coordinates {\n')
for value in values:
f.write(f' ({value[0]}, {value[1]["querying"][0]})\n')
f.write(' };\n')
# CPU time plots
f.write(' \\addplot+[ybar, fill=red!50] plot coordinates {\n')
for value in values:
f.write(f' ({value[0]}, {value[1]["loading"][1]})\n')
f.write(' };\n')
f.write(' \\addplot+[ybar, fill=red!25] plot coordinates {\n')
for value in values:
f.write(f' ({value[0]}, {value[1]["querying"][1]})\n')
f.write(' };\n')
f.write(' \\legend{Real-Time (Loading), Real-Time (Querying), CPU Time (Loading), CPU Time (Querying)}\n')
f.write(' \\end{axis}\n')
f.write('\\end{tikzpicture}\n')
f.write('\\end{document}\n')
처리되는 데이터의 구조는 다음과 같습니다.
{
(<env_name>, <graph_type>, <mode>): [(<graph_size>, {'loading': (<real_time>, <cpu_time>), 'querying': (<real_time>, <cpu_time>)}),...]
}
이것을 달성할 수 있는 방법이 있나요? 나는 항상 하나의 막대로만 쌓을 수 있었습니다.
업데이트:실시간 데이터를 누적(하단에 로드, 상단에 쿼리)하고 싶습니다. 이 스케치에 표시된 것처럼 CPU 시간에도 동일하게 적용됩니다.
답변1
두 개의 누적된 막대 차트를 나란히 놓으려면 약간의 노력이 필요해 보입니다. 예를 참조하십시오Jake의 이 솔루션또는톰 봄바딜의 것.
따라서 디버깅에 이러한 노력과 시간을 소비하고 싶지 않다면 동일한 데이터 소스에서 두 개의 다이어그램을 그리는 것이 좋습니다.관심 있는 분들을 위해, 이 개념 변경은 최소한 복사를 하지 않고 복사하는 발명 원리의 패턴을 따릅니다.
몇 가지 발언.
데이터 파일
나는 다음과 같은 데이터 구조를 가정합니다.
\begin{filecontents}{data2.dat}
time lrt lct qrt qct
10 5 4 3 3
20 7 5 4 3
30 4 7 5 2
\end{filecontents}
여기에서는 데이터가 .tex 파일에만 포함되어 있지만 data3.dat
디렉토리에 etc만 두고 해당 데이터를 로드할 수 있습니다. 아래를 참조하세요.
처음 두 열은 마지막 두 열과 마찬가지로 함께 속한다고 가정합니다. 그것이 틀렸다면 y=
아래 할당을 변경하십시오.
\addplot-s
열별로 플롯합니다. 예를 들어 여기서는 두 번째 이름이 입니다 lrt
. 파일 이름을 귀하의 이름으로 바꾸십시오. 데이터에 헤더가 포함되어 있음을 프로그램에 알립니다.
\addplot table[header=true,x=time,y=lrt]{data2.dat};% i.e. your data file
중심선
데모의 경우 제목에 쉼표가 포함된 경우 모든 항목을 { }
. 두 개의 bar 문이 필요합니다. 유용한 라벨을 붙이세요. 범례 항목은 단지 더미일 뿐입니다. 더 나은 이름을 사용하세요.
\begin{axis}[
title={Real-time data, Load},
ybar stacked,
stack plots=y,
xmin=0, xmax=50,
xlabel=time (s),
ylabel=percent,
legend entries={lrt, lct},% replace by better names
]
향후 개선 제안
- 데이터 파일 이름을 로 옮기고
\newcommand
,\addplot
s에서 바꾸면 한 곳에서만 변경할 수 있습니다. - 두 플롯의 색 구성표를 변경합니다(설명서 참조).
- 범례를 외부로 이동합니다(매뉴얼 참조).
- 필요에 따라 다이어그램의 너비와 높이를 조정하세요.
article
당신에게 적합하다면 수업이나 이와 유사한 수업 에 참여하십시오 . 독립 실행형은 2개의 이미지를 생성합니다(설명서 참조).- 예를 들어 검색 엔진의 검색어를 통해 ctan에서 매뉴얼을 찾으세요.
ctan pgfplots
- 데이터의 잘못된 시각화를 방지하려면 시간 간격이 변경되지 않도록 하세요.
\documentclass[10pt,border=3mm,tikz]{standalone}
\usepackage{pgfplots}
\begin{document}
% ~~~ pretending you have said file in your directory
% assuming lrt= load real timeetc.
% assuming, this is your data structure
\begin{filecontents}{data2.dat}
time lrt lct qrt qct
10 5 4 3 3
20 7 5 4 3
30 4 7 5 2
\end{filecontents}
% ~~~ Concept: Draw two diagrams
\begin{tikzpicture} % LOAD
\begin{axis}[
title={Real-time data, Load},
ybar stacked,
stack plots=y,
xmin=0, xmax=50,
xlabel=time (s),
ylabel=percent,
legend entries={lrt, lct},% replace by better names
]
\addplot table[header=true,x=time,y=lrt]{data2.dat};% i.e. your data file
\addplot table[header=true,x=time,y=lct]{data2.dat};
\end{axis}
\end{tikzpicture}
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
\begin{tikzpicture} % CPU
\begin{axis}[
title={Real-time data, CPU},
ybar stacked,
stack plots=y,
xmin=0, xmax=50,
xlabel=time (s),
ylabel=percent,
legend entries={qrt,qct},
]
\addplot table[header=true,x=time,y=qrt]{data2.dat};
\addplot table[header=true,x=time,y=qct]{data2.dat};
\end{axis}
\end{tikzpicture}
\end{document}
답변2
MS-SPO 답변나를 가리켰다제이크의 솔루션이 라텍스 코드를 생성하는 데 사용되었습니다.
\documentclass[border=10pt]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.18}
\makeatletter
\newcommand\resetstackedplots{
\pgfplots@stacked@isfirstplottrue
\addplot [forget plot,draw=none] coordinates{(10,0) (20,0)};
}
\begin{document}
\begin{tikzpicture}
\begin{axis}[
ybar stacked,
title={Performance charts},
height=0.019\textheight, width=1.5\textwidth,
bar width=0.8cm,
ymajorgrids, tick align=inside,
major grid style={draw=gray!20},
xtick=data,
ymin=0,
axis x line*=bottom,
axis y line*=left,
enlarge x limits=0.4,
legend entries={
Real Time (Loading),
Real Time (Querying),
CPU Time (Loading),
CPU Time (Querying),
},
legend style={
at={(0.5,-0.2)},
anchor=north,
legend columns=-1,
},
ylabel={Time (seconds)},
xlabel={Graph Size},
symbolic x coords={
10,
20,
},
]
\addplot +[bar shift=-.5cm] coordinates {
(10, 0.001223850250244141)
(20, 0.001497483253479004)
};
\addplot +[bar shift=-.5cm] coordinates {
(10, 0.00045402050018310557)
(20, 0.001987481117248536)
};
\resetstackedplots
\addplot +[bar shift=.5cm] coordinates {
(10, 0.0008006999999999999)
(20, 0.0010588)
};
\addplot +[bar shift=.5cm] coordinates {
(10, 0.0002661999999999997)
(20, 0.0012075)
};
\end{axis}
\end{tikzpicture}
\end{document}
코드는 다음 차트를 생성했습니다.
이에 의해 동적으로 생성되었습니다.파이썬 함수.