Plotly 공부

강민수·2023년 2월 20일
0

1. 그래프 출력

  • histogram
#case 1: express를 사용

counts = df['child_num'].value_counts()

fig1 = px.histogram(counts, x=counts.index, y=counts.values, nbins=len(counts))
fig1.update_layout(yaxis={'title': 'count'},xaxis={'title':'child_num'})
#fig1.update_layout(yaxis_title='count',xaxis_title='child_num') 위와 같은 표현
fig1.show()


#case 2: go를 사용
fig1 = go.Figure(data=[go.Histogram(x=df['child_num'])])

fig1.update_layout(
    title='Number of Children Histogram',
    xaxis_title='Number of Children',
    yaxis_title='Count'
)
fig1.show()


#case 3: go를 사용
# Create a histogram of the counts
trace = go.Histogram(x=df['child_num'])
layout = go.Layout(
    title='Number of Children Histogram',
    xaxis_title='Number of Children',
    yaxis_title='Count'
)
# Show the plot
fig = go.Figure(data=[trace],layout=layout)
fig.show()

2. SubPlot

fig = make_subplots(rows=1, cols=2)

# Add the histograms to the subplot
fig.add_trace(fig1['data'][0], row=1, col=1)
fig.add_trace(fig2['data'][0], row=1, col=2)

# Set the layout of the subplot
fig.update_layout()

fig.update_xaxes(title_text="Number of children", row=1, col=1)
fig.update_yaxes(title_text="Count", row=1, col=1)

fig.update_xaxes(title_text="Number of gender", row=1, col=2)
fig.update_yaxes(title_text="Count", row=1, col=2)

# Display the subplot
fig.show()
  • showlegend를 통해 오른쪽에 legend를 나오게 할 수 있다.
  • col과 row가 (0,0)이 아니라 (1,1)에서 부터 시작된다
종합 예제
histogram_list=['gender','car','child_num','income_type','edu_type','family_type','house_type','FLAG_MOBIL','work_phone','phone','email','family_size']
fig = make_subplots(rows=math.ceil(len(histogram_list)/2),cols=2)

fig_layout = go.Layout(
    title='Histograms',
    height=3000,
    width=1500,
    #showlegend=False
) #전체 그래프에 대한 layout

for i in range(len(histogram_list)):
    trace = go.Histogram(x=df[histogram_list[i]])

    tmp = go.Figure(data=[trace])
    
    fig.add_trace(tmp['data'][0],row=i//2+1,col=i%2+1)

    fig.update_xaxes(title_text="Number of "+histogram_list[i], row=i//2+1, col=i%2+1)
    fig.update_yaxes(title_text="Count", row=i//2+1, col=i%2+1)

    fig.update_layout()

fig.update_layout(fig_layout)
fig.show()

0개의 댓글