서브 플롯의 한 틱에서만 matplotlib를 사용하여 트리 플롯의 소수 자릿수 변경

유 필라 트 13

저는 우리가 3 배라고 부르는 것을 플로팅하고 있습니다. 즉, 공분산과 사후 분포를 나타내는 몇 쌍의 매개 변수가있는 공동 sitribution입니다. 다른 서브 플롯으로 구성됩니다.

처음에는 트리 플롯의 y 축에있는 서브 플롯에서 다음과 같은 기본 xticks를 얻습니다.

여기에 이미지 설명 입력

내가하고 싶은 것은 평균 xtick 값 0.00000.00.

이를 위해 그리고 내 연구에서 (Latex 글꼴을 유지하면서) 다음을 발견했습니다.

## If we are on third line of triplot
if (m == 3):
  ax.yaxis.set_major_formatter(FormatStrFormatter(r'$%.2f$')) (1)

문제는 이제 다음과 같은 서브 플롯이 있다는 것입니다.

여기에 이미지 설명 입력

보시다시피 다른 두 xtick 값도 형식의 영향을받는 %.2f반면이 형식을 평균 ( 0.00) 에 사용하고 싶습니다 .

제한을 유지하고 표시 만 할 ±0.1864소수 자릿수 만 변경하려면 어떻게해야 합니까?0.00000.00

나는 모든 y를 따라 올바른 xtick ( " mean[m]"로 인덱싱 된 코드에서 " " 라고 부르는 것을 선택해야한다고 생각합니다. m여기서 " m"는 삼중 서브 플롯 (여기서는 열 인덱스가 0 = 첫 번째 열)의 행을 나타냄)을 나타냄) 축이지만이 축에서 위치를 찾는 방법을 모르겠습니다.

(1) 명령 줄에 몇 가지 옵션을 추가 / 수정하여이 값만 변경하는 방법을 볼 수 있다면 감사하겠습니다.

업데이트 1 : 답변 해 주셔서 감사합니다. 실제로 GetDist 도구를 사용하고 있습니다 ( GetDist 예제에 대한 예제 포함 ).

처음에는 "w_a"매개 변수 (위 그림의 왼쪽에있는 레이블)에 4 대신 소수점 2 자리를 사용하면 "w_a"레이블이 오른쪽으로 이동 될 것이라고 생각했습니다.

실제로이 레이블 "w_a"가 Ox 및 Oy 축 모두에서 다른 모든 레이블과 비교하여 잘못 정렬 된 것을 볼 수있는 전체 삼각형 플롯 아래에 표시 됩니다. Ox 축에서는 "w_a"가 정렬되지 않고 Oy에서는 "-0.1864"및 "0.1864"(대부분 0.1864 앞의 마이너스 부호 이후로 생각됨) 이후 왼쪽 정렬됩니다.

모든 레이블을 Ox 및 Oy 축과 일정한 간격으로 정렬하는 트릭 / 솔루션이 있다고 생각하십니까? 나는 각 상자의 3 xtick에 대해 2 또는 4 소수를 취한다는 사실과는 별개로 의미합니다.

삼각 플롯

UPDATE 2: I have found a solution that we can qualify of "tricky" or "dirty" solution.

I played with set_label_coords on xaxis and yaxis and set manually the padding which gives a good rendering.

g = plots.get_subplot_plotter()
g.settings.constrained_layout = True

# Call triplot
g.triangle_plot([matrix1, matrix2],
                names,
                filled = True,
                legend_labels = ['1240', '1560'],
                legend_loc = 'upper right',
                contour_colors = ['red','darkblue'],
                line_args = [{'lw':2, 'color':'red'},
                {'lw':2, 'color':'darkblue'}],
                )

# Browse each subplot of triangle
for m in range(0,7):
  for n in range(0,m+1):
    ax = g.subplots[m,n]

    # First joint disctibution : row = 1 (second line) and column = 0 (first column)
    if (m == 1 and n == 0):
      x0, y0 = ax.yaxis.get_label().get_position()

    if (m != n):
      if (m == 3 and n == 0):
        # shift on the left w_a label
        ax.yaxis.set_label_coords(x0-0.55, y0)

        # Joint disctibution : row = 3 (fourth line) and column = 0 (first column)
        # 0.0 for w_a
        ax.yaxis.set_major_formatter(FuncFormatter(lambda x,_: '$0.0$' if x == 0 else f'${x:.4f}$'))
       
      # Joint disctibution : row = 6 (seventh line) and column = 3 (fourth column)

      if (m == 6 and n == 3):
        # shift on bottom w_a label
        ax.xaxis.set_label_coords(x0+0.5, y0-1)
      elif (n == 3):
        ax.xaxis.set_major_formatter(FuncFormatter(lambda x,_: '$0.0$' if x == 0 else f'${x:.4f}$'))

Here is the result :

까다로운 솔루션

As you can see, this is a fine-tuned solution since I have to iteratively change the padding to get in agreement with all the other labels from a global alignment point of view.

My original idea was to store the coordinates of the first label on each axis and apply these coordinates to all other labels on each side subplots.

But unfortunately, I get for each side subplots for y-axis :

x0 = 0, y0 = 0.5

and for x-axis : x0 = 0.5 and y0 = 0

So, If I apply these coordinates, the labels are over on x-axis/y-axis and I am obliged to shift horizontally (for y-axis) and vertically (for x-axis) the labels.

But the ideal would be to have an automatic way to align all the labels at the same space between labels and axis. I keep on my research.

UPDATE 3: I tried to apply the solution given by @JohanCwith the following code snippet at the end of my script :

for ax in g.fig.axes:
    ylabel = ax.get_ylabel()
    if len(ylabel) > 0:
        ylbl = ax.yaxis.get_label()
        ax.yaxis.labelpad = ylbl.get_position()[0] + 30

Here the results :

안녕하세요.

As you can see, an extra padding is appearing for "w_a" parameter compared to all the others labels.

I think that extra-padding is simply caused by the value -0.1864 on the y-axis of subplot corresponding to "w_a" label, especially by the sign "minus" which pushes the label to the left, always compared to the others labels which have 4 decimals without sign "minus".

I don't know how to force the label "w_a" to be located like the other ones (this is your code snippet).

Is there an alternative way to do this forcing ?

PS : maybe if I can't force the same location for "w_a" parameter**, I could include in the @JohanC solution, i.e in the for ax in g.fig.axes: a condition dedicated for "w_a" by making decrease the labelpad and then set it roughly to the same labelpad than the other labels.

UPDATE 4 : Following the advices of JohanC, I dit at the end of my script :

for ax in g.fig.axes:
    ylabel = ax.get_ylabel()
    if len(ylabel) > 0:
        ylbl = ax.yaxis.get_label()
        ax.yaxis.labelpad = ylbl.get_position()[0] + 30

# Redraw the plot
plt.draw()
# Save triplot
g.export('Final_Figure.pdf')

But the Final_figure.pdf is not changing the shift of "w_a" (left shift for Oy axis and bottom shift for Ox axis), below the result :

항상 "w_a"매개 변수로 이동

I don't know currently what to try anything else.

Stef

You could use a FuncFormatter:

from matplotlib.ticker import FuncFormatter

ax.yaxis.set_major_formatter(FuncFormatter(lambda x,_: '0.00' if x == 0 else f'{x:.4f}'))

As for your updated (actual) question: you could use align_labels().

Example:

from getdist import plots, MCSamples
import getdist
import matplotlib.pyplot as plt
import numpy as np
ndim = 4
nsamp = 1000
np.random.seed(10)
A = np.random.rand(ndim,ndim)
cov = np.dot(A, A.T)
samps = np.random.multivariate_normal([0]*ndim, cov, size=nsamp)
samps[:,1]-=100000
A = np.random.rand(ndim,ndim)
cov = np.dot(A, A.T)
samps2 = np.random.multivariate_normal([0]*ndim, cov, size=nsamp)
names = ["x%s"%i for i in range(ndim)]
labels =  ["x_%s"%i for i in range(ndim)]
samples = MCSamples(samples=samps,names = names, labels = labels)
samples2 = MCSamples(samples=samps2,names = names, labels = labels, label='Second set')
g = plots.get_subplot_plotter()
g.settings.axis_tick_x_rotation=45
g.triangle_plot([samples, samples2], filled=True)

여기에 이미지 설명 입력

Then after g.fig.align_labels(): 여기에 이미지 설명 입력

(이는 g.export('Final_Figure.pdf')또는로 저장된 pdf에 유지됩니다 g.fig.savefig('Final_Figure.pdf')).

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

3 개의 변수를 사용하여 R에서 플롯 만들기

분류에서Dev

격자 패키지를 사용하여 xyplot에서 요인 변수의 플롯 순서 변경

분류에서Dev

Matplotlib 서브 플롯 사용자 정의

분류에서Dev

matplotlib 서브 플롯의 수직 배열

분류에서Dev

과학적 표기법 플롯에서 서브 플롯의 소수 자릿수

분류에서Dev

ggparty가있는 의사 결정 트리 플롯의 모서리에있는 소수 자릿수

분류에서Dev

matplotlib의 등고선 플롯에서 조건부 함수 변경

분류에서Dev

Gnuplot에서 for 루프의 동일한 플롯에 함수를 여러 번 플롯하는 방법

분류에서Dev

matplotlib의 플롯에서 두 숫자 사이의 분할 수 늘리기

분류에서Dev

shiny 또는 flexdahsboard에서 사용자가 선택한 변수의 플롯 차트를 만드는 방법은 무엇입니까?

분류에서Dev

하나가 imshow 플롯 인 경우 matplotlib에서 수직으로 두 개의 플롯을 정렬합니까?

분류에서Dev

bayesboot 함수의 플롯에서 xlab을 변경하십시오.

분류에서Dev

Matplotlib를 사용하여 날짜에 대한 사망 수 플롯

분류에서Dev

Matlab에서 syms 변수를 사용하여 플롯 결과 변경

분류에서Dev

동일한 플롯에서 두 변수의 빈도 분포 곡선 그리기

분류에서Dev

Pyplot에서 이미 플롯 된 플롯의 선 너비를 어떻게 변경할 수 있습니까?

분류에서Dev

matplotlib에서 서브 플롯 사이의 수직 공간 줄이기

분류에서Dev

Matplotlib : 서브 플롯의 가변 크기?

분류에서Dev

플롯의 "% {variable}"구문에서 사용할 수있는 변수

분류에서Dev

R에서 ggplot2를 사용하여 두 변수의 방향 화살표 플롯 생성

분류에서Dev

ggplot2 : 막대 플롯을 동일한 위치에 유지하면서 포인트 플롯의 위치를 변경하는 방법

분류에서Dev

플롯 사용자 정의 버튼 : 여러 서브 플롯에 동일한 스케일을 설정할 수 있습니까?

분류에서Dev

단일 막대 차트에서 여러 범주 형 변수의 서브 플롯 개수

분류에서Dev

파이썬에서 통합의 변수 제한으로 플롯

분류에서Dev

Pandas DataFrame 플롯 함수를 사용하여 서브 플롯 당 ylabel을 그리는 방법

분류에서Dev

matplotlib, 두 플롯의 공간을 차지하는 서브 플롯

분류에서Dev

플롯 된 Y 이외의 변수를 사용하여 누적 막대 차트에 레이블 지정

분류에서Dev

for 루프를 사용하여 matplotlib의 서브 플롯에 고유 한 제목 추가

분류에서Dev

다양한 서브 플롯에서 다양한 연속 변수의 밀도 플로팅

Related 관련 기사

  1. 1

    3 개의 변수를 사용하여 R에서 플롯 만들기

  2. 2

    격자 패키지를 사용하여 xyplot에서 요인 변수의 플롯 순서 변경

  3. 3

    Matplotlib 서브 플롯 사용자 정의

  4. 4

    matplotlib 서브 플롯의 수직 배열

  5. 5

    과학적 표기법 플롯에서 서브 플롯의 소수 자릿수

  6. 6

    ggparty가있는 의사 결정 트리 플롯의 모서리에있는 소수 자릿수

  7. 7

    matplotlib의 등고선 플롯에서 조건부 함수 변경

  8. 8

    Gnuplot에서 for 루프의 동일한 플롯에 함수를 여러 번 플롯하는 방법

  9. 9

    matplotlib의 플롯에서 두 숫자 사이의 분할 수 늘리기

  10. 10

    shiny 또는 flexdahsboard에서 사용자가 선택한 변수의 플롯 차트를 만드는 방법은 무엇입니까?

  11. 11

    하나가 imshow 플롯 인 경우 matplotlib에서 수직으로 두 개의 플롯을 정렬합니까?

  12. 12

    bayesboot 함수의 플롯에서 xlab을 변경하십시오.

  13. 13

    Matplotlib를 사용하여 날짜에 대한 사망 수 플롯

  14. 14

    Matlab에서 syms 변수를 사용하여 플롯 결과 변경

  15. 15

    동일한 플롯에서 두 변수의 빈도 분포 곡선 그리기

  16. 16

    Pyplot에서 이미 플롯 된 플롯의 선 너비를 어떻게 변경할 수 있습니까?

  17. 17

    matplotlib에서 서브 플롯 사이의 수직 공간 줄이기

  18. 18

    Matplotlib : 서브 플롯의 가변 크기?

  19. 19

    플롯의 "% {variable}"구문에서 사용할 수있는 변수

  20. 20

    R에서 ggplot2를 사용하여 두 변수의 방향 화살표 플롯 생성

  21. 21

    ggplot2 : 막대 플롯을 동일한 위치에 유지하면서 포인트 플롯의 위치를 변경하는 방법

  22. 22

    플롯 사용자 정의 버튼 : 여러 서브 플롯에 동일한 스케일을 설정할 수 있습니까?

  23. 23

    단일 막대 차트에서 여러 범주 형 변수의 서브 플롯 개수

  24. 24

    파이썬에서 통합의 변수 제한으로 플롯

  25. 25

    Pandas DataFrame 플롯 함수를 사용하여 서브 플롯 당 ylabel을 그리는 방법

  26. 26

    matplotlib, 두 플롯의 공간을 차지하는 서브 플롯

  27. 27

    플롯 된 Y 이외의 변수를 사용하여 누적 막대 차트에 레이블 지정

  28. 28

    for 루프를 사용하여 matplotlib의 서브 플롯에 고유 한 제목 추가

  29. 29

    다양한 서브 플롯에서 다양한 연속 변수의 밀도 플로팅

뜨겁다태그

보관