시각화 | Matplotlib 기초

matplotlib 라이브러리 기본 사용법

matplotlib: 파이썬에서 데이터를 그래프나 차트로 시각화할 수 있는 라이브러리


import matplotlib.pyplot as plt

그래프 그리기

두 가지 방법이 있다.

  1. plt.plot()
  2. plt.subplots()

1. plt.plot()

state machine interface 방식

선(또는 점) 그래프

# plt.plot(x, y)
x = list(map(int, range(5))) # [0, 1, 2, 3, 4]
y = list(map(int, range(4, 9))) # [4, 5, 6, 7, 8]

plt.plot(x, y)

그래프 결과

해상도, 타이틀, 범주 등

### fig: 크기 조절, dpi: 해상도 설정(default: 100)
plt.figure(figsize=(4, 4), dpi=200) 

### plot 라벨 범주 표현하기
plt.plot(x, y, label="x-y")
plt.plot(x, z, label="x-z")
plt.legend(loc="lower right") 

### 그래프 타이틀
plt.title("[Example Plot]")

### x, y 라벨
plt.xlabel("X")
plt.ylabel("Y")

# 좌표평면 범위 조절
plt.ylim([0, 10])

# 눈금 추가/삭제 (스타일마다 default가 다름)
plt.grid()

범주, 타이틀, 라벨 예시

Line Style

x, y = np.array(x), np.array(y)

plt.plot(x, y,  linestyle="-", marker="o")
plt.plot(x, y+1, linestyle="--", marker="^")
plt.plot(x, y+2, linestyle="-.", marker="*")
plt.plot(x, y+3, linestyle=":")

line style, marker 예시

2. plt.subplots()

object oriented interface 방식

# fig, ax = plt.subplots()
x = list(map(int, range(5))) # [0, 1, 2, 3, 4]
y = list(map(int, range(4, 9))) # [4, 5, 6, 7, 8]
z = list(map(int, range(2, 7))) # [2, 3, 4, 5, 6]

fig, ax = plt.subplots()
ax.plot(x, y)
  • fig: 전체 figure, 도화지라고 생각
  • ax: 그래프 객체
  • 하나의 fig에 여러 개의 그래프를 그릴 수 있다.
  • 하나의 ax에 여러 개의 선을 나타낼 수 있다.

subplots(nrow, ncols) 그리드 지정

#### plt.subplots(nrows=1, ncols=1) # int, default:1

fig, axes = plt.subplots(2, 1) # 2행 1열 그리드 (위 아래)

# 그래프 그리기
axes[0].plot(x, y)
axes[1].plot(x, z)

그리드 지정 그래프

subplots() 그래프 예시

plt.plot()으로 그리는 것과 동일하게 여러가지 옵션을 줄 수 있다.

x = np.arange(10)
fig, ax = plt.subplots()

ax.plot(
    x, x, label='y=x',
    marker='o',
    color='blue',
    linestyle=':'
)
ax.plot(
    x, x**2, label='y=x^2',
    marker='^',
    color='red',
    linestyle='--'
)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend(
    loc='upper left',
    shadow=True,
    fancybox=True,
    borderpad=2
)

subplots() 옵션 예시


그래프 테마

단순히 그래프 선 색깔을 바꾸는 것 말고도 다양한 테마를 제공한다.

matplotlib stylesheet에서 다양한 스타일을 고를 수 있다.

import matplotlib.pyplot as plt

# 'seaborn' 스타일 사용 선언
plt.style.use("ggplot")

나는 ggplot이나 seaborn이 제일 예쁘고 눈에 잘 들어오는 듯

ggplot 스타일시트


다른 그래프: Scatter, Bar, Histogram

1. Scatter 그래프

plt.figure(figsize=(4, 4), dpi=100) # fig 크기 조절, 해상도 설정

plt.scatter(x, y, alpha=0.8, marker="*") # alpha: 투명도

산점도 그래프 예시

pandas.DataFrame 산점도 그래프

import pandas as pd

df = pd.DataFrame(np.random.rand(100, 2)); 
print(df)

plt.scatter(df[0], df[1])

산점도 그래프 예시2

2. Bar 그래프

plt.bar(x=np.arange(5), height=3*x-1)

막대 그래프 예시

3. Histogram 그래프

plt.hist([1, 1, 1, 2, 3, 4, 2, 5])
# 값들에 대한 통계 (빈도수)

히스토그램 예시


Reference

  • 다양한 matplotlib 예제를 보고 싶다면: example

Baisc | Python lambda

파이썬 람다식 배우기

람다식은 맨날 봐도봐도 익숙하지 않고 문법도 헷갈린다.
이참에 정리를 해야지.

lambda = 한 줄 함수

lambda 매개변수 : 표현식

labmda 활용 예시

1. 두 수를 더하는 함수

def _adder(x, y):
  return x+y

adder = (lambda x,y: x+y)

# 사용 예시
a = _adder(1, 3)
b = adder(1, 3)
# a = b

2. 제곱 함수

def _square(x):
  return x*x

square = (lambda x: x*x)

3. if-else를 포함한 함수

# 매개변수로 받은 문자열의 첫 글자를 반환, 빈 문자열인 경우 빈 문자열 반환
def _first_letter(s):
  return s[0] if s else ""

first_letter = (lambda s: s[0] if s else "")

생략이 많다.

  • 함수 이름 필요 없음
  • return 키워드 필요 없음

매개변수 부분이 입력(in) 표현식 부분이 반환(out)

map vs. list comprehension

map()은 데이터 구조의 각 원소들에 동일한 함수를 적용하여 새로운 데이터를 만든다.

# 아래의 두 줄은 유사한 연산을 수행
>>> [func(x) for x in data]
>>> map(func, data)

차이점

연산 진행 시점

map()은 데이터가 필요해질 때 연산 수행

filter()

Introducing Hydejack 9

Introducing Hydejack 9

Version 9 is the most complete version of Hydejack yet. Modernized design, big headlines, and big new features.

Version 9 is the most complete version of Hydejack yet.

Modernized design, big headlines, big new features: Built-In Search, Sticky Table of Contents, and Auto-Hiding Navbar. That and more is Hydejack 9.

Linking in Style

Ever since the introduction of Dark Mode, link styles have been a bit of an issue. Specifically, finding an accent color that worked on both light and dark backgrounds was the problem. With Hydejack 9, the link style has been revamped so that legibility is no longer tied to the choice of accent_color, giving you much more freedom in creating a unique design flavor for your site.

Ready for the Big Screen

The theme on which Hydejack is based was designed for a different era of the web. Hydejack has inherited many of its limitations, but over time I’ve made adjustments, such as centering the content column for better reading ergonomics.

With version 9, Hydejack takes full advantage of large displays. Whether it’s design indulgences such as oversized headlines, or quality of life improvements such as a floating table of contents, Hydejack now finds use for all that extra screen real estate1.

What’s in the Cards?

Hydejack 9 now lets you use content cards for both projects and posts. The cards have been redesigned with a new hover style and drop shadows and they retain their unique transition-to-next-page animations, which now also work on the blog layout. The new grid layout lets you do that.

Good images are key to making the most out of content cards. For that reason, a chapter on images has been added to the documentation.

Hydejack now has Built-In Search. It even works offline. I’ve been prototyping many approaches and eventually settled on a fully client-side, off-the-main thread solution that perfectly fits the use case of personal sites and shows surprisingly good results2.

The new search UI is custom made for Hydejack and shows beautiful previews of your posts and pages, right on top of your regular content.

Together with the Auto-Hiding Navbar, your entire content library is now only a couple of keystrokes away.

Auto-Hiding Navbar

A navbar that’s there when you need it, and disappears when you don’t. Simple as that.

Sticky Table of Contents

Already a staple on so many sites on the web, this pattern is now also available in Hydejack. What’s unique about it is that it simply picks up the table of contents already created by kramdown’s {:toc} tag and transparently upgrades it to a fully dynamic version.

…and much more

Other noteworthy changes include:

  • Support for Jekyll 4
  • Choice between MathJax and KaTeX for math rendering
  • Use of jekyll-include-cache for drastically improved page building speeds
  • New variables configuration file — adjust content width, sidebar width, font size, etc…
  • …and the option to disable grouping projects by year.

Read the the CHANGELOG for the full scope of features and improvements made in Hydejack 9. Maybe just glance at it to confirm that it is indeed a pretty long list.

Even More to Come

New features for 9.1 are already lined up. Code block headers and code line highlights for even better technical blogging, as well as download buttons on the resume page for PDF, vCard, and Resume JSON are just around the corner.

Get It Now

The Free Version of Hydejack is now availabe on RubyGems and for the first time also on GitHub Packages. The source code is available on GitHub as always.

The PRO Version is scheduled to release on July 7th on Gumroad. Pre-Orders are open now:

  1. If you are a fan of the old two-column layout, or don’t like modern design tropes such as mega headlines, Hydejack lets you revert these changes on a case-by-case basis via configuration options. ↩︎

  2. Search was mainly tested for English and German. Please let me know about issues in other languages. While I’ve tried to find a multi-language solution, most showed drastically worse results for the English base case. If you’re technically inclined, you can adopt the code located in _includes/js/search-worker.js to your needs. ↩︎

Example Content III

Example Content III

A page showing Hydejack-specific markdown content.

Hydejack offers a few additional features to markup your markdown. Don’t worry, these are merely CSS classes added with kramdown’s {:...} syntax, so that your content remains compatible with other Jekyll themes.

Large Tables

Default alignedLeft alignedCenter alignedRight alignedDefault alignedLeft alignedCenter alignedRight alignedDefault alignedLeft alignedCenter alignedRight alignedDefault alignedLeft alignedCenter alignedRight aligned
First body partSecond cellThird cellfourth cellFirst body partSecond cellThird cellfourth cellFirst body partSecond cellThird cellfourth cellFirst body partSecond cellThird cellfourth cell
Second linefoostrongbazSecond linefoostrongbazSecond linefoostrongbazSecond linefoostrongbaz
Third linequuxbazbarThird linequuxbazbarThird linequuxbazbarThird linequuxbazbar
Second body   Second body   Second body   Second body   
2 line   2 line   2 line   2 line   
Footer row   Footer row   Footer row   Footer row   

Code blocks

// Example can be run directly in your JavaScript console

// Create a function that takes two arguments and returns the sum of those
// arguments
var adder = new Function("a", "b", "return a + b");

// Call the function
adder(2, 6);
// > 8

Math

Lorem ipsum \(f(x) = x^2\). \[\begin{aligned} \phi(x,y) &= \phi \left(\sum_{i=1}^n x_ie_i, \sum_{j=1}^n y_je_j \right) \\[2em] &= \sum_{i=1}^n \sum_{j=1}^n x_i y_j \phi(e_i, e_j) \\[2em] &= (x_1, \ldots, x_n) \left(\begin{array}{ccc} \phi(e_1, e_1) & \cdots & \phi(e_1, e_n) \\ \vdots & \ddots & \vdots \\ \phi(e_n, e_1) & \cdots & \phi(e_n, e_n) \end{array}\right) \left(\begin{array}{c} y_1 \\ \vdots \\ y_n \end{array}\right) \end{aligned}\]

Message boxes

NOTE: You can add a message box.

Large text

You can add large text.

Large images

Full-width image

Captions to images

Full-width image A caption to an image.

Large quotes

You can make a quote “pop out”.

Faded text

I’m faded, faded, faded.

Example Content II

Example Content II

A page showing how regular markdown content is styled in Hydejack.

There should be whitespace between paragraphs. We recommend including a README, or a file with information about your project.

There should be whitespace between paragraphs.

Text can be bold, italic, or strikethrough.

Link to another page.

Header 2

This is a normal paragraph following a header. GitHub is a code hosting platform for version control and collaboration. It lets you and others work together on projects from anywhere.

Header 3

This is a blockquote following a header.

When something is important enough, you do it even if the odds are not in your favor.

// Javascript code with syntax highlighting.
var fun = function lang(l) {
  dateformat.i18n = require('./lang/' + l)
  return true;
}
# Ruby code with syntax highlighting
GitHubPages::Dependencies.gems.each do |gem, version|
  s.add_dependency(gem, "= #{version}")
end

Header 4

  • This is an unordered list following a header.
  • This is an unordered list following a header.
  • This is an unordered list following a header.
Header 5
  1. This is an ordered list following a header.
  2. This is an ordered list following a header.
  3. This is an ordered list following a header.
Header 6
head1head twothree
okgood swedish fishnice
out of stockgood and plentynice
okgood oreoshmm
okgood zoute dropyumm

There’s a horizontal rule below this.


Here is an unordered list:

  • Item foo
  • Item bar
  • Item baz
  • Item zip

And an ordered list:

  1. Item one
  2. Item two
  3. Item three
  4. Item four

And a nested list:

  • level 1 item
    • level 2 item
    • level 2 item
      • level 3 item
      • level 3 item
  • level 1 item
    • level 2 item
    • level 2 item
    • level 2 item
  • level 1 item
    • level 2 item
    • level 2 item
  • level 1 item

Small image

Large image

Definition lists

Name
Godzilla
Born
1952
Birthplace
Japan
Color
Green
Long, single-line code blocks should not wrap. They should horizontally scroll if they are too long. This line should be long enough to demonstrate this. Or is it?
The final element.

Example Content

Howdy! This is an example blog post that shows several types of HTML content supported in this theme.

Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eu leo quam. Pellentesque ornare sem lacinia quam venenatis vestibulum. Sed posuere consectetur est at lobortis. Cras mattis consectetur purus sit amet fermentum.

Curabitur blandit tempus porttitor. Nullam quis risus eget urna mollis ornare vel eu leo. Nullam id dolor id nibh ultricies vehicula ut id elit.

Etiam porta sem malesuada magna mollis euismod. Cras mattis consectetur purus sit amet fermentum. Aenean lacinia bibendum nulla sed consectetur.

Inline HTML elements

HTML defines a long list of available inline tags, a complete list of which can be found on the Mozilla Developer Network.

  • To bold text, use **To bold text**.
  • To italicize text, use *To italicize text*.
  • Abbreviations, like HTML should be defined like this *[HTML]: HyperText Markup Language.
  • Citations, like — Mark otto, should use <cite>.
  • Deleted text should use ~~deleted~~ and inserted text should use <ins>.
  • Superscript text uses <sup> and subscript text uses <sub>.

Most of these elements are styled by browsers with few modifications on our part.

Heading 2

Vivamus sagittis lacus vel augue rutrum faucibus dolor auctor. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Morbi leo risus, porta ac consectetur ac, vestibulum at eros.

Heading 3

Vivamus sagittis lacus vel augue rutrum faucibus dolor auctor.

Heading 4

Vivamus sagittis lacus vel augue rutrum faucibus dolor auctor.

Heading 5

Vivamus sagittis lacus vel augue rutrum faucibus dolor auctor.

Heading 6

Vivamus sagittis lacus vel augue rutrum faucibus dolor auctor.

Code

Cum sociis natoque penatibus et magnis dis code element montes, nascetur ridiculus mus.

// Example can be run directly in your JavaScript console

// Create a function that takes two arguments and returns the sum of those
// arguments
var adder = new Function("a", "b", "return a + b");

// Call the function
adder(2, 6);
// > 8

Lists

Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean lacinia bibendum nulla sed consectetur. Etiam porta sem malesuada magna mollis euismod. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.

  • Praesent commodo cursus magna, vel scelerisque nisl consectetur et.
  • Donec id elit non mi porta gravida at eget metus.
  • Nulla vitae elit libero, a pharetra augue.

Donec ullamcorper nulla non metus auctor fringilla. Nulla vitae elit libero, a pharetra augue.

  1. Vestibulum id ligula porta felis euismod semper.
  2. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
  3. Maecenas sed diam eget risus varius blandit sit amet non magna.

Cras mattis consectetur purus sit amet fermentum. Sed posuere consectetur est at lobortis.

HyperText Markup Language (HTML)
The language used to describe and define the content of a Web page
Cascading Style Sheets (CSS)
Used to describe the appearance of Web content
JavaScript (JS)
The programming language used to build advanced Web sites and applications

Integer posuere erat a ante venenatis dapibus posuere velit aliquet. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Nullam quis risus eget urna mollis ornare vel eu leo.

Images

Quisque consequat sapien eget quam rhoncus, sit amet laoreet diam tempus. Aliquam aliquam metus erat, a pulvinar turpis suscipit at.

800x400

400x200

200x200

Tables

Aenean lacinia bibendum nulla sed consectetur. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

NameUpvotesDownvotes
Alice1011
Bob43
Charlie79
Totals2123

Nullam id dolor id nibh ultricies vehicula ut id elit. Sed posuere consectetur est at lobortis. Nullam quis risus eget urna mollis ornare vel eu leo.

Pagination