2017-02-23 2 views
0

누적 막대 그래프에서 작업 중입니다. 알 수 있듯이 몇 가지 문제가 있습니다. enter image description here 1) 테이블의 색상에 알파를 어떻게 추가 할 수 있습니까? 에 alpha=0.75을 추가하려고했지만 아무 것도하지 않았습니다.
2) 텍스트에 맞게 표의 행 높이를 늘리려면 어떻게해야합니까?
3) '3/1'막대를 어떻게 테이블 열의 가운데에 배치 할 수 있습니까?
4) 범례를 그래프 위로 가운데로 이동하려면 어떻게해야합니까?
5) 전설이 잘리는 문제를 어떻게 해결할 수 있습니까? & # 2 # 3
용액 :Matplot 테이블, 범례, 누적 막대 그래프 문제

import matplotlib.pyplot as plt 
import numpy as np 

res = (0, 21) 
canc = (21, 0) 
me = (37, 37) 
ee = (4, 4) 
sw = (16, 16) 
te = (31, 31) 
spec = (1, 1) 
sys = (2, 2) 
lm = (9, 9) 

data = [res, canc, me, ee, sw, te, spec, sys, lm] 
labels = ['Resolved', 'To be cancelled', 'Mech Eng', 'Elec Eng', 'Software', 'Test Eng', 'Specialty', 'Systems', 'LM Review'] 
dates = ('2/22', '3/1 (Projected)') 

fig, ax = plt.subplots() 

index = np.arange(len(dates)) 
bar_width = 0.25 
y_offset = np.array([0.0] * len(dates)) 

gray = plt.cm.gray(0.5) 
yellow = plt.cm.hot(0.9) 
green = plt.cm.Greens(0.5) 
magenta = plt.cm.RdPu(0.5) 
orange = plt.cm.Oranges(0.5) 
purple = plt.cm.Purples(0.5) 
greenblue = plt.cm.GnBu(0.4) 
red = plt.cm.Reds(0.5) 
blue = plt.cm.Blues(0.5) 
colors = [gray, yellow, green, magenta, orange, purple, greenblue, red, blue] 

cell_text = [] 
for row in range(len(data)): 
    plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[row], alpha=0.75, align='center', label=labels[row]) 
    y_offset = y_offset + data[row] 

colors = colors[::-1] 
data.reverse() 
labels.reverse() 

the_table = plt.table(cellText=data, rowLabels=labels, rowColours=colors, alpha=0.1, colLabels=dates, loc='bottom', cellLoc='center') 
the_table.scale(1, 1.6) 

plt.ylabel('Open Items') 

plt.subplots_adjust(left=0.2, bottom=0.35) 

plt.xticks([]) 
plt.yticks(np.arange(0, 130, 5)) 
ax.set_xlim(-0.5, 1.5) 
plt.legend() 

handles, labels = ax.get_legend_handles_labels() 
ax.legend(handles[::-1], labels[::-1], bbox_to_anchor=(1., 1.15), ncol=4) 

plt.show() 

EDIT : 실측치 여기

제가 가지고있는 코드이다.
# 1에 대한 해결 방법이지만 색상을 지정하는 대신 실제로 알파를 적용 할 수 있기를 원합니다.
내가 원하는 곳에 전설이 있지만 지금은 잘립니다.

답변

1

1) 알파 추가 : 각 색상의 알파 채널을 사용할 수 있습니다. 이 작업은 색상을 rgba로 변환 한 다음 튜플의 알파를 원하는 값으로 설정하여 수행됩니다.

alpha = 0.75 
colors = ['gray', 'yellow', 'green'] 
cols=[] 
for c in colors: 
    col = list(matplotlib.colors.to_rgba(c)) 
    col[3] = alpha 
    cols.append(col) 

2) 그래프 위 센터 전설 : 이것은 모든 비트는 그림 크기, 글꼴 크기 등 최적의 매개 변수가 시행 착오에 의해 발견 될 필요가 있으므로에 따라되지만, 아이디어는을 배치 할 수 있습니다 (x = 0.5) 및 그 위에 (y = 1.0) 범례의 바운딩 상자를 지정하고 loc 매개 변수를 'lower center'으로 지정합니다. 이는 범례의 맨 아래 가운데가 그 지점에 있어야 함을 의미합니다. y을 약간 더 크게하면 범례와 축 사이에 약간의 패딩이 생성됩니다.

이것은 모든 그림이 캔버스에 맞도록 그림 크기를 조정 한 완전한 스크립트입니다.

import matplotlib.pyplot as plt 
import numpy as np 
import matplotlib.colors 

res = (0, 21) 
canc = (21, 0) 
me = (37, 37) 
ee = (4, 4) 
sw = (16, 16) 
te = (31, 31) 
spec = (1, 1) 
sys = (2, 2) 
lm = (9, 9) 

data = [res, canc, me, ee, sw, te, spec, sys, lm] 
labels = ['Resolved', 'To be cancelled', 'Mech Eng', 'Elec Eng', 'Software', 'Test Eng', 'Specialty', 'Systems', 'LM Review'] 
dates = ('2/22', '3/1 (Projected)') 

fig, ax = plt.subplots(figsize=(6,6)) #<- set figure size large enough for data 

index = np.arange(len(dates)) 
bar_width = 0.25 
y_offset = np.array([0.0] * len(dates)) 

# set alpha to colors: 
alpha = 0.75 
colors = ['gray', 'yellow', 'green', 'magenta', 'orange', 'palevioletred', 'mediumspringgreen', 'red', 'blue'] 
cols=[] 
for c in colors: 
    col = list(matplotlib.colors.to_rgba(c)) 
    col[3] = alpha 
    cols.append(col) 
colors = cols[::-1] 

cell_text = [] 
for row in range(len(data)):        #colors need to be inverted here as well, don't they? 
    plt.bar(index, data[row], bar_width, bottom=y_offset, color=colors[::-1][row], alpha=0.75, align='center', label=labels[row]) 
    y_offset = y_offset + data[row] 


data.reverse() 
labels.reverse() 

the_table = plt.table(cellText=data, rowLabels=labels, rowColours=colors, alpha=0.1, colLabels=dates, loc='bottom', cellLoc='center') 
the_table.scale(1, 1.6) 

plt.ylabel('Open Items') 

plt.subplots_adjust(left=0.22, bottom=0.35, right=0.78, top=0.82) # <- allocate some spacing for legend on top and on right as well 

plt.xticks([]) 
plt.yticks(np.arange(0, 130, 5)) 
ax.set_xlim(-0.5, 1.5) 
#plt.legend() <- remove, we only need one single legend defined below 

handles, labels = ax.get_legend_handles_labels() 
# loc=8 means the bbox ccordinates define the lower center of the legend 
# so placing it at x=0.5 (horizontal center of the axes), y=1.02 (vertical top of the axes) 
ax.legend(handles[::-1], labels[::-1], loc=8, bbox_to_anchor=(0.5, 1.02), ncol=4) 

plt.show() 

enter image description here

+0

감사합니다. 그래도 오류가 발생합니다 :'AttributeError : 'module'객체에는 'to_rgba'속성이 없습니다. 버전 1.5가 설치되어있는 것처럼 보이고'to_rgba'는 버전 2.0 일뿐입니다. – drewd423

+0

그럴 수 있습니다. 'matplotlib.colors.colorConverter.to_rgba (c)'가 대신 작동합니까? – ImportanceOfBeingErnest

+0

그렇지 않습니다. 지금 2.0을 다운로드하고 설치하려고합니다. – drewd423