2017-10-02 11 views
0

예를 들어, 나는 해당 색상의 육각형의 육각형 모양의 격자를 대표 다음과 같은 좌표가있는 경우 :6 각형 그리드 모양으로 (x, y, z) 좌표를 그리는 방법은 무엇입니까?

coord = [[0,0,0],[0,1,-1],[-1,1,0],[-1,0,1],[0,-1,1],[1,-1,0],[1,0,-1]] 
colors = [["Green"],["Blue"],["Green"],["Green"],["Red"],["Green"],["Green"]] 

어떻게 파이썬에서 하나의 플롯이 플롯 포인트는 육각형 모양을 유지할 수 있도록? 또한 육각형에 '색상'목록을 어떻게 표현할 수 있습니까? 다소 이런

: 어디에서 하나를 볼 수있는 단지 있도록

간단한 육각형 격자

그러나 모양은 중요하지 않습니다, 그냥 간단한 산포도 형 시각화, 충분 다른 육각형과의 관계는 그 색이 있습니다.

+0

ASCII를 사용하고 있습니까? 아니면 거북이 그래픽 모듈을 사용 하시겠습니까? – EgMusic

+0

좌표는 무엇을 나타내는가? 이미지와 'coord'를 연결할 수 없습니다. 여기에서 사용 된 규칙을 말하고 싶을 것입니다. ''[[a, b, c], [d, e, f]]'리스트를 취하면 a, b, c, d, e, f는 무엇입니까? – ImportanceOfBeingErnest

+0

@ChaseBarnes 가장 간단한 해결책을 사용하고 싶습니다. ASCII이면 충분합니다. – ishido

답변

1

육각형의 (y, z) 좌표를 matplotlib 축의 y 직교 좌표로 변환하면됩니다.

나는 그렇게 할 수있는 올바른 방법이 공식을 사용하고있는 것 :

y_cartesian = (2/3) * sin(60) * (y_hex - z_hex) 

당신은 다음하기 matplotlib RegularPolygon 패치를 사용하여 육각형을 추가하거나 scatter을 사용하여 센터를 플롯 할 수 있습니다.

는 여기에 귀하의 목록에서 플롯을 만들 수있는 스크립트입니다 :

import matplotlib.pyplot as plt 
from matplotlib.patches import RegularPolygon 
import numpy as np 

coord = [[0,0,0],[0,1,-1],[-1,1,0],[-1,0,1],[0,-1,1],[1,-1,0],[1,0,-1]] 
colors = [["Green"],["Blue"],["Green"],["Green"],["Red"],["Green"],["Green"]] 
labels = [['yes'],['no'],['yes'],['no'],['yes'],['no'],['no']] 

# Horizontal cartesian coords 
hcoord = [c[0] for c in coord] 

# Vertical cartersian coords 
vcoord = [2. * np.sin(np.radians(60)) * (c[1] - c[2]) /3. for c in coord] 

fig, ax = plt.subplots(1) 
ax.set_aspect('equal') 

# Add some coloured hexagons 
for x, y, c, l in zip(hcoord, vcoord, colors, labels): 
    color = c[0].lower() # matplotlib understands lower case words for colours 
    hex = RegularPolygon((x, y), numVertices=6, radius=2./3., 
         orientation=np.radians(30), 
         facecolor=color, alpha=0.2, edgecolor='k') 
    ax.add_patch(hex) 
    # Also add a text label 
    ax.text(x, y+0.2, l[0], ha='center', va='center', size=20) 

# Also add scatter points in hexagon centres 
ax.scatter(hcoord, vcoord, c=[c[0].lower() for c in colors], alpha=0.5) 

plt.show() 

enter image description here

+0

고맙습니다. 각 육각형에 레이블을 추가로 붙일 수 있습니까? label = [[yes]], [no], [yes], [no], [yes], [no], [no] ']]'. 나는'RegularPolygon'이 레이블 옵션을 가지고 있음을 보았습니다. – ishido

+1

'RegularPolygon'에'label '을 쓰는 것은 범례에 레이블을 넣는 것이라고 생각합니다. 대신에,'ax.text (x, y, label)'를 사용할 수 있습니다. 내 편집보기 – tom

2

여기 직교 좌표로 좌표 진수의 (U, V, W) 튜플을 변환하는 기능입니다. 표준 turtle 모듈을 사용하여 설명 할 것입니다 (저는 matplotlib 모듈이 없습니다). 각 점이 올바른 위치에 플롯되었는지 쉽게 확인할 수 있도록 목록의 색상을 변경했습니다.

import turtle 
from math import sqrt 

root3 = sqrt(3) 

# the scale used for drawing 
side = 50 

# Convert hex coordinates to rectangular 
def hex_to_rect(coord): 
    u, v, w = coord 
    x = u - v/2 - w/2 
    y = (v - w) * root3/2 
    return x * side, y * side 

# Initialize the turtle 
t = turtle.Turtle() 
t.speed(0) 
t.hideturtle() 
t.up() 

coords = [[0,0,0], [0,1,-1], [-1,1,0], [-1,0,1], [0,-1,1], [1,-1,0], [1,0,-1]] 
colors = ['black', 'red', 'orange', 'green', 'cyan', 'blue', 'magenta'] 

#Plot the points 
for hexcoord, color in zip(coords, colors): 
    xy = hex_to_rect(hexcoord) 
    t.goto(xy) 
    t.dot(15, color) 

# Wait for the user to close the window 
turtle.done() 

출력

다음

dots on a hexagonal grid

+0

@Chase Barnes 오타를 수정 해 주셔서 감사합니다. 그러나 matplotlib 설치에 대한 정보는 제 대답과는 전혀 관련이 없습니다. –

+0

사람들이 모듈을 설치하는 방법을 알고 싶어하는 경우를 위해, 이해합니다. – EgMusic

+0

문제를 읽었을 때 [0, -1, 1], 즉 하단 위치에 시안 색 원을 표시해야하는 녹색 원이 표시됩니다. – cdlane

1

PM2Ring의 거북이 기반 솔루션 (+1)을 마무리뿐만 아니라 내가 그의 대답에 좌표 계산 오류로 보는 것을 해결하기 위해 내 시도는 다음과 같습니다

from math import sqrt 
from turtle import Turtle, Screen 

ROOT3_OVER_2 = sqrt(3)/2 

FONT_SIZE = 18 
FONT = ('Arial', FONT_SIZE, 'normal') 

SIDE = 50 # the scale used for drawing 

# Convert hex coordinates to rectangular 
def hex_to_rect(coord): 
    v, u, w = coord 
    x = -u/2 + v - w/2 
    y = (u - w) * ROOT3_OVER_2 
    return x * SIDE, y * SIDE 

def hexagon(turtle, radius, color, label): 
    clone = turtle.clone() # so we don't affect turtle's state 
    xpos, ypos = clone.position() 
    clone.setposition(xpos - radius/2, ypos - ROOT3_OVER_2 * radius) 
    clone.setheading(-30) 
    clone.color('black', color) 
    clone.pendown() 
    clone.begin_fill() 
    clone.circle(radius, steps=6) 
    clone.end_fill() 
    clone.penup() 
    clone.setposition(xpos, ypos - FONT_SIZE/2) 
    clone.write(label, align="center", font=FONT) 

# Initialize the turtle 
tortoise = Turtle(visible=False) 
tortoise.speed('fastest') 
tortoise.penup() 

coords = [[0, 0, 0], [0, 1, -1], [-1, 1, 0], [-1, 0, 1], [0, -1, 1], [1, -1, 0], [1, 0, -1]] 
colors = ["Green", "Blue", "Green", "Green", "Red", "Green", "Green"] 
labels = ['yes', 'no', 'yes', 'no', 'yes', 'no', 'no'] 

# Plot the points 
for hexcoord, color, label in zip(coords, colors, labels): 
    tortoise.goto(hex_to_rect(hexcoord)) 
    hexagon(tortoise, SIDE, color, label) 

# Wait for the user to close the window 
screen = Screen() 
screen.exitonclick() 

enter image description here