레이블, 제목, 그림 저장
축 레이블, 제목, 범례, 눈금 형식을 추가한 다음 savefig()로 출판 품질의 그림을 저장합니다.
레이블, 제목, 그림 저장은(는) CoddyKit의 무료 Pandas & NumPy Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Pandas & NumPy Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
From Plot to Publication
A chart is only effective if its axes are labelled, its title explains the takeaway, and it is saved at high enough resolution for its intended medium. This lesson covers the finishing touches that transform a quick exploratory plot into a polished figure suitable for a report, dashboard, or academic publication: axis labels, tick formatting, titles, legends, annotations, and file export.
Axis Labels with set_xlabel and set_ylabel
Set descriptive axis labels with ax.set_xlabel() and ax.set_ylabel(). Always include units in the label (e.g., 'Revenue (USD)' rather than just 'Revenue'). Use fontsize to make labels larger for presentations, and labelpad to add space between the axis and the label text when ticks are large.
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(7, 4))
x = np.arange(1, 13)
y = np.random.randint(100, 500, 12)
ax.plot(x, y, 'o-', color='steelblue')
ax.set_xlabel('Month', fontsize=12, labelpad=8)
ax.set_ylabel('Revenue (USD thousands)', fontsize=12, labelpad=8)
# plt.show()
plt.close()Titles with set_title and suptitle
ax.set_title() sets the title above a single Axes. For multi-panel figures, fig.suptitle() adds a shared title above all subplots. Control font size with fontsize and vertical position with y (default 1.0). A good title states the main insight of the chart, not just what the axes are — compare 'Monthly Revenue' to 'Revenue Peaked in Q3 and Fell 20% in Q4'.
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
ax1.plot([1,2,3], [1,4,9])
ax1.set_title('Subplot One', fontsize=11)
ax2.bar(['A','B','C'], [3,7,2])
ax2.set_title('Subplot Two', fontsize=11)
# Shared figure title
fig.suptitle('Annual Overview Dashboard', fontsize=14, fontweight='bold', y=1.02)
plt.tight_layout()
plt.close()Controlling Tick Labels
Matplotlib's default tick labels are often adequate, but sometimes you need custom labels. Use ax.set_xticks() to specify tick positions and ax.set_xticklabels() to set the labels. Pass rotation=45 to tilt long labels so they do not overlap. The ha='right' (horizontal alignment) parameter ensures rotated labels anchor correctly to their tick mark.
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
values = np.random.randint(200, 600, 12)
fig, ax = plt.subplots(figsize=(9, 4))
ax.bar(range(12), values, color='steelblue')
ax.set_xticks(range(12))
ax.set_xticklabels(months, rotation=45, ha='right', fontsize=10)
ax.set_ylabel('Revenue')
plt.tight_layout()
plt.close()Formatting Tick Values
Use matplotlib.ticker formatters to display tick values in a human-readable format. FuncFormatter takes a function that receives the tick value and returns a formatted string. Common patterns: thousands separator, currency symbol, percentage sign, scientific notation. Apply with ax.yaxis.set_major_formatter(formatter).
from matplotlib.ticker import FuncFormatter
def millions_fmt(x, pos):
return f'${x/1e6:.1f}M'
fig, ax = plt.subplots(figsize=(7, 4))
ax.bar(['Q1', 'Q2', 'Q3', 'Q4'], [1.2e6, 1.8e6, 2.1e6, 1.9e6], color='steelblue')
ax.yaxis.set_major_formatter(FuncFormatter(millions_fmt))
ax.set_title('Quarterly Revenue')
ax.set_ylabel('Revenue')
plt.tight_layout()
plt.close()Legends with ax.legend()
Call ax.legend() to display a legend for all plot elements that have a label parameter set. Customise with loc (position, e.g., 'upper right', 'lower left'), ncol (number of columns), framealpha (box transparency), and fontsize. Placing the legend outside the plot area uses bbox_to_anchor combined with loc.
fig, ax = plt.subplots(figsize=(7, 4))
for region, color in [('East','steelblue'),('West','coral'),('North','green')]:
ax.plot(range(12), np.random.randint(100, 400, 12),
marker='o', label=region, color=color)
ax.legend(loc='upper right', ncol=1, framealpha=0.8, fontsize=10)
ax.set_title('Monthly Sales by Region')
plt.close()Adding Text Annotations
ax.annotate(text, xy=(x_point, y_point), xytext=(x_text, y_text), arrowprops=...) adds a text label with an optional arrow pointing to a specific data point. Use this to highlight maximum values, anomalies, or important events on a chart. The arrowprops dict controls the arrow style: arrowstyle='->' is a simple arrow.
y_vals = np.array([120, 180, 310, 250, 420, 380, 290])
x_vals = np.arange(len(y_vals))
peak_idx = np.argmax(y_vals)
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x_vals, y_vals, 'o-', color='steelblue')
ax.annotate(f'Peak: {y_vals[peak_idx]}',
xy=(peak_idx, y_vals[peak_idx]),
xytext=(peak_idx - 2, y_vals[peak_idx] + 30),
arrowprops={'arrowstyle': '->', 'color': 'red'},
fontsize=10, color='red')
plt.close()Adding Horizontal and Vertical Reference Lines
ax.axhline(y_value) draws a horizontal line across the full width of the Axes at the specified y-value. ax.axvline(x_value) draws a vertical line. Both accept color, linestyle, and linewidth parameters. Reference lines are commonly used to mark targets, thresholds, or event dates on time series charts.
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(range(10), np.random.randint(100, 400, 10), 'o-', color='steelblue')
# Target line
ax.axhline(y=250, color='red', linestyle='--', lw=1.5, label='Target')
# Event line
ax.axvline(x=5, color='orange', linestyle=':', lw=1.5, label='Campaign start')
ax.legend()
ax.set_title('Revenue vs Target')
plt.close()Styling with Themes
Matplotlib includes several built-in style sheets that change the overall look of all figures without code changes: 'seaborn-v0_8-whitegrid', 'fivethirtyeight', 'ggplot', 'bmh', etc. Apply a style with plt.style.use('style_name') at the start of your script. Use plt.style.context('style_name') as a context manager to apply a style only within a block.
# Apply a style globally
plt.style.use('seaborn-v0_8-whitegrid')
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(range(10), np.random.randn(10).cumsum())
ax.set_title('Seaborn Whitegrid Style')
plt.close()
# Reset to default
plt.rcdefaults()Saving Figures with savefig()
fig.savefig('filename.png') saves the figure to a file. Key parameters: dpi (dots per inch — use 150 for screen, 300 for print), bbox_inches='tight' (prevents labels from being clipped), and format (inferred from the extension or specified explicitly). Common formats: '.png' (raster, good for web), '.pdf' (vector, good for print), '.svg' (vector, editable in Illustrator).
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(range(10), np.random.randn(10), 'o-')
ax.set_title('Export Example')
ax.set_xlabel('Step')
ax.set_ylabel('Value')
# Save as PNG (screen quality)
fig.savefig('/tmp/chart_screen.png', dpi=150, bbox_inches='tight')
# Save as PDF (print quality)
fig.savefig('/tmp/chart_print.pdf', dpi=300, bbox_inches='tight')
plt.close()
print('Figures saved.')Complete Example: Polished Report Chart
Here is a complete workflow combining all the techniques in this lesson: a polished time series chart with axis labels, formatted y-axis ticks, a horizontal target line, an annotation on the peak, and export to a high-resolution PNG. This is the pattern you will use for any chart that goes into a report or dashboard.
from matplotlib.ticker import FuncFormatter
fig, ax = plt.subplots(figsize=(9, 5))
months = list(range(1, 13))
revenue = [120, 145, 132, 160, 175, 190, 210, 185, 220, 200, 240, 260]
peak = max(revenue)
peak_idx = revenue.index(peak)
ax.plot(months, revenue, 'o-', color='steelblue', lw=2, markersize=6)
ax.axhline(y=180, color='red', ls='--', lw=1.2, label='Target: $180K')
ax.annotate(f'Peak ${peak}K', xy=(peak_idx+1, peak),
xytext=(peak_idx-1.5, peak+15),
arrowprops={'arrowstyle': '->'}, fontsize=9)
ax.set_xticks(months)
ax.set_xticklabels(['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'], rotation=45, ha='right')
ax.yaxis.set_major_formatter(FuncFormatter(lambda x,p: f'${x:.0f}K'))
ax.set_title('2024 Monthly Revenue vs Target', fontsize=13, fontweight='bold')
ax.set_ylabel('Revenue')
ax.legend()
plt.tight_layout()
plt.close()Quick Check
Test your understanding of labels, titles, and saving figures from this lesson.
Lesson Recap
In this lesson you learned: set_xlabel()/set_ylabel()/set_title() add descriptive text; FuncFormatter formats tick values as currency or percentages; ax.annotate() adds pointed text labels to highlight key data points; axhline()/axvline() draw reference lines; and fig.savefig() with dpi and bbox_inches='tight' produces publication-quality exports. This completes the Matplotlib Fundamentals course — next up is Seaborn for statistical plots.
자주 묻는 질문
“레이블, 제목, 그림 저장” 강의는 무료인가요?
네 — “레이블, 제목, 그림 저장” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Pandas & NumPy Academy 강의 전체를 잠금 해제할 수 있습니다. Pandas & NumPy Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“레이블, 제목, 그림 저장”에서 뭘 배우나요?
축 레이블, 제목, 범례, 눈금 형식을 추가한 다음 savefig()로 출판 품질의 그림을 저장합니다. 브라우저에서 직접 실행하는 실습 코드로 Pandas & NumPy Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Pandas & NumPy Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Pandas & NumPy Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“레이블, 제목, 그림 저장” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Pandas & NumPy Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Pandas & NumPy Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Figure와 Axes 구조
- 선 그래프와 산점도
- 막대 그래프와 히스토그램
- 레이블, 제목, 그림 저장