在轴值之间放置标签并添加第二个Y轴

huangapple go评论54阅读模式
英文:

How to put labels between axis values and add a second Y axis

问题

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

state_palette = list((sns.color_palette("Spectral_r", 5).as_hex()))
action_palette = list((sns.color_palette("Spectral_r", 4).as_hex()))

# create data for E=0.1 Sigmoid/Golabi States
x = ['0.2', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0 \n (Linear model)']

states = np.c_[st_02, st_05, st_06, st_07, st_08, st_09, st_10]

# plot bars in stack manner
plt.figure(figsize=(6, 18))
plt.subplot(8, 1, 8)
#y1
plt.bar(x, states[0], label='State 1', color=state_palette[0])
plt.bar(x, states[1], bottom=states[0], label='State 2', color=state_palette[1])
plt.bar(x, states[2], bottom=states[0]+states[1], label='State 3', color=state_palette[2])
plt.bar(x, states[3], bottom=states[0]+states[1]+states[2], label='State 4', color=state_palette[3])
plt.bar(x, states[4], bottom=states[0]+states[1]+states[2]+states[3], label='State 5', color=state_palette[4])
plt.gca().invert_xaxis()
plt.ylim([0, 8])
plt.ylabel('Fraction of states')
plt.xlabel('Economies of scale parameter, b')

# Adding the second Y-axis
ax = plt.gca().twinx()
ax.set_ylim([0, 1])
ax.set_ylabel('Fraction of states (normalized)')

plt.legend(bbox_to_anchor=(0, 1.02, 1, 0.2), loc="lower left", mode="expand", borderaxespad=0, ncol=3)

plt.show()
英文:

I have a numpy 2d-array from which I generate the following graph.

Stacked 8 year state distribution for different parameter b

The graph basically explains how system takes 5 states over 8 time intervals for different system parameter b.

It is a bit confusing because fractions go from 0 to 8 which isn't entirely correct. I want the fractions to go from 0 to 1 and then another Y axis that specifies the year. Basically correctly label the graph so new readers don't get confused.

How do I go about it?

Code attached below. I think I could have looped through the data but it is what it is...

Data

import numpy as np

st_02 =  np.array( [[0.00000000e+00, 0.00000000e+00, 3.00000000e-01, 3.00000000e-01, 4.00000000e-01],
 [3.97179162e-01, 9.99999998e-09, 1.49999990e-01, 3.90000000e-01, 6.28208384e-02],
 [5.09153766e-01, 1.58871677e-01, 1.34153757e-01, 1.04999974e-01, 9.28208264e-02],
 [1.52746140e-01, 2.35435852e-01, 3.03484421e-01, 1.88681959e-01, 1.19651568e-01],
 [4.58238520e-02, 1.08185636e-01, 3.23255031e-01, 3.72735451e-01, 1.50000033e-01],
 [1.37471656e-02, 2.33919697e-01, 3.57054740e-01, 2.45278398e-01, 1.50000033e-01],
 [4.12415968e-03, 2.66515660e-01, 3.85409213e-01, 1.93950958e-01, 1.50000000e-01],
 [3.00000000e-01, 5.49528058e-02, 1.55510049e-01, 3.89537165e-01, 1.00000000e-01]] ).reshape((40,1))

act_02 =  np.array( [[3.02820848e-01, 0.00000000e+00, 3.00000000e-01, 3.97179152e-01],
 [6.09999990e-01, 0.00000000e+00, 9.99999998e-09, 3.90000000e-01],
 [8.95000027e-01, 0.00000000e+00, 1.04999974e-01, 0.00000000e+00],
 [5.07833560e-01, 3.03484421e-01, 1.88681959e-01, 0.00000000e+00],
 [3.04009522e-01, 0.00000000e+00, 6.95990482e-01, 0.00000000e+00],
 [3.97666896e-01, 0.00000000e+00, 6.02333138e-01, 0.00000000e+00],
 [4.95560235e-01, 0.00000000e+00, 3.54439755e-01, 1.50000000e-01],
 [1.00000002e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00]]  ).reshape((32,1))

st_05 =  np.array( [[0.00000000e+00, 0.00000000e+00, 3.00000000e-01, 3.00000000e-01, 4.00000000e-01],
 [3.97179162e-01, 9.99999998e-09, 1.49999990e-01, 3.90000000e-01, 6.28208384e-02],
 [5.09153766e-01, 1.58871677e-01, 1.34153757e-01, 1.04999974e-01, 9.28208264e-02],
 [1.52746140e-01, 2.35435852e-01, 3.03484421e-01, 1.88681959e-01, 1.19651568e-01],
 [4.58238520e-02, 1.08185636e-01, 3.23255031e-01, 3.72735451e-01, 1.50000033e-01],
 [1.37471656e-02, 2.33919697e-01, 3.57054740e-01, 2.45278398e-01, 1.50000033e-01],
 [4.12415968e-03, 2.66515660e-01, 3.85409213e-01, 1.93950958e-01, 1.50000000e-01],
 [3.00000000e-01, 5.49528058e-02, 1.55510049e-01, 3.89537165e-01, 1.00000000e-01]] ).reshape((40,1))

act_05 =  np.array( [[3.02820848e-01, 0.00000000e+00, 3.00000000e-01, 3.97179152e-01],
 [6.09999990e-01, 0.00000000e+00, 9.99999998e-09, 3.90000000e-01],
 [8.95000027e-01, 0.00000000e+00, 1.04999974e-01, 0.00000000e+00],
 [5.07833560e-01, 3.03484421e-01, 1.88681959e-01, 0.00000000e+00],
 [3.04009522e-01, 0.00000000e+00, 6.95990482e-01, 0.00000000e+00],
 [3.97666896e-01, 0.00000000e+00, 6.02333138e-01, 0.00000000e+00],
 [4.95560235e-01, 0.00000000e+00, 3.54439755e-01, 1.50000000e-01],
 [1.00000002e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00]]  ).reshape((32,1))

st_06 =  np.array(  [[1.00000000e-08, 1.00000000e-08, 3.00000000e-01, 3.00000000e-01, 3.99999980e-01],
 [3.99999993e-01, 1.60000000e-08, 1.33743840e-01, 3.69679758e-01, 9.65763937e-02],
 [4.89679778e-01, 1.60000010e-01, 1.33374292e-01, 9.36206777e-02, 1.23325152e-01],
 [1.46903944e-01, 2.27871923e-01, 2.93689650e-01, 1.81534423e-01, 1.50000000e-01],
 [1.02809113e-01, 1.04335972e-01, 2.82777081e-01, 3.60077804e-01, 1.50000010e-01],
 [3.90920537e-01, 2.31657098e-01, 2.06555160e-01, 2.08672044e-02, 1.50000010e-01],
 [1.17276161e-01, 3.26632740e-01, 3.47239376e-01, 5.88517223e-02, 1.50000000e-01],
 [3.00000000e-01, 1.12237023e-01, 1.89735546e-01, 2.98027461e-01, 1.00000000e-01]] ).reshape((40,1))

act_06 =  np.array(  [[3.40640469e-01, 0.00000000e+00, 2.59359551e-01, 3.99999980e-01],
 [6.30320226e-01, 0.00000000e+00, 1.60000000e-08, 3.69679758e-01],
 [9.06379232e-01, 0.00000000e+00, 9.36206777e-02, 0.00000000e+00],
 [7.59727597e-01, 0.00000000e+00, 1.81534423e-01, 5.87379200e-02],
 [3.57145095e-01, 0.00000000e+00, 2.82777081e-01, 3.60077804e-01],
 [7.72577646e-01, 0.00000000e+00, 2.27422364e-01, 0.00000000e+00],
 [6.81573667e-01, 0.00000000e+00, 1.68426333e-01, 1.50000000e-01],
 [1.00000003e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00]]   ).reshape((32,1))

st_07 =  np.array( [[1.00000000e-08, 1.00017172e-08, 3.00000000e-01, 3.00000000e-01, 3.99999980e-01],
 [3.99999993e-01, 1.60003434e-08, 1.20731694e-01, 3.53414616e-01, 1.25853675e-01],
 [4.73414624e-01, 1.60000010e-01, 1.32073187e-01, 8.45121789e-02, 1.50000000e-01],
 [2.95048729e-01, 2.21365842e-01, 2.51231702e-01, 1.32600008e-01, 9.97536896e-02],
 [8.85146287e-02, 1.62292670e-01, 2.99497287e-01, 2.99695354e-01, 1.50000020e-01],
 [3.26249753e-01, 2.47562768e-01, 2.43728915e-01, 3.24584740e-02, 1.50000010e-01],
 [9.78749359e-02, 3.26249814e-01, 3.56887552e-01, 6.89876479e-02, 1.50000000e-01],
 [3.00000000e-01, 1.04399947e-01, 1.85196960e-01, 3.10403093e-01, 1.00000000e-01]]  ).reshape((40,1))

act_07 =  np.array( [[0.37317078, 0.,         0.22682924, 0.39999998],
 [0.64658538, 0.,         0.,         0.35341462],
 [0.84697567, 0.,         0.,         0.15302433],
 [0.86739996, 0.,         0.13260001, 0.        ],
 [0.40080732, 0.,         0.29949729, 0.29969535],
 [0.72381253, 0.,         0.27618739, 0.        ],
 [0.66201817, 0.,         0.18798178, 0.15      ],
 [1.,         0.,         0.,         0.        ]]  ).reshape((32,1))

st_08 =  np.array( [[1.00000000e-08, 2.00005688e-08, 3.00000000e-01, 3.00000000e-01, 3.99999980e-01],
 [6.06666639e-01, 1.80001138e-08, 3.00000050e-02, 2.19333347e-01, 1.44000009e-01],
 [4.01333361e-01, 2.42666649e-01, 1.84999993e-01, 2.09999971e-02, 1.50000000e-01],
 [2.33199972e-01, 2.09066664e-01, 2.84499987e-01, 1.80133315e-01, 9.31000126e-02],
 [6.99600015e-02, 1.35093342e-01, 2.95903305e-01, 3.49043302e-01, 1.50000010e-01],
 [3.70031303e-01, 2.32544662e-01, 2.20405317e-01, 2.70186583e-02, 1.50000000e-01],
 [1.79407247e-01, 1.94521463e-01, 2.72576730e-01, 2.03494530e-01, 1.50000000e-01],
 [3.00000000e-01, 1.10667201e-01, 1.86841779e-01, 3.02491020e-01, 1.00000000e-01]] ).reshape((40,1))

act_08 =  np.array( [[0.39333338, 0.,         0.,         0.60666663],
 [0.78066667, 0.,         0.,         0.21933335],
 [0.88720003, 0.,         0.,         0.11279997],
 [0.81986664, 0.,         0.18013331, 0.        ],
 [0.35505335, 0.,         0.2959033,  0.3490433 ],
 [0.93160209, 0.,         0.,         0.06839785],
 [0.57682169, 0.,         0.27317828, 0.15      ],
 [1.,         0.,         0.,         0.        ]]  ).reshape((32,1))

st_09 =  np.array(  [[0.,         0.,         0.3,        0.3,        0.39999998],
 [0.60000003, 0.,         0.02999999, 0.22000001, 0.15      ],
 [0.406,      0.24,       0.18299999, 0.02099998, 0.15      ],
 [0.17729999, 0.21040001, 0.28409999, 0.17819998, 0.15      ],
 [0.27785663, 0.11300001, 0.20784001, 0.25130335, 0.15000001],
 [0.33466034, 0.25844667, 0.23429301, 0.02259995, 0.15      ],
 [0.1567521,  0.18555348, 0.28371522, 0.2239792,  0.15      ],
 [0.3,        0.09981155, 0.21590587, 0.28428259, 0.1       ]]  ).reshape((40,1))

act_09 =  np.array( [[0.40000001, 0.,         0.,         0.59999997],
 [0.77400003, 0.,         0.,         0.226     ],
 [0.94449999, 0.,         0.,         0.05549998],
 [0.77533334, 0.,         0.,         0.22466663],
 [0.54085665, 0.,         0.20784001, 0.25130335],
 [0.93159647, 0.,         0.01204951, 0.05635399],
 [0.6740841,  0.,         0.07294154, 0.25297436],
 [1.00000001, 0.,         0.,         0.        ]]   ).reshape((32,1))

st_10 =  np.array( [[1.00000000e-08, 1.00000000e-08, 3.00000000e-01, 3.00000000e-01, 3.99999980e-01],
 [5.99999982e-01, 5.99998334e-09, 2.99999990e-02, 2.19999993e-01, 1.50000000e-01],
 [3.89999986e-01, 2.40000004e-01, 1.82999988e-01, 3.69999916e-02, 1.50000000e-01],
 [1.86899986e-01, 2.04000005e-01, 2.79300007e-01, 1.79800002e-01, 1.50000000e-01],
 [2.81270038e-01, 1.15559985e-01, 2.06399990e-01, 2.46769997e-01, 1.50000000e-01],
 [3.60351005e-01, 1.35620022e-01, 1.74356992e-01, 1.79671981e-01, 1.50000000e-01],
 [1.42976700e-01, 1.71264396e-01, 2.78781796e-01, 2.56977077e-01, 1.50000000e-01],
 [3.00000000e-01, 9.14435692e-02, 2.13814032e-01, 2.94742399e-01, 1.00000000e-01]]  ).reshape((40,1))

act_10 =  np.array(  [[0.40000003, 0.,         0.,         0.59999997],
 [0.79,       0.,         0.,         0.20999998],
 [0.93009999, 0.,         0.,         0.06989998],
 [0.77480001, 0.,         0.,         0.22519999],
 [0.72403003, 0.,         0.,         0.27596998],
 [0.78545663, 0.,         0.17967198, 0.03487139],
 [0.64218250, 0.,         0.10071049, 0.25710698],
 [1.,         0.,         0.,         0.        ]]   ).reshape((32,1))

Plotting

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

state_palette = list((sns.color_palette("Spectral_r", 5).as_hex()))
action_palette = list((sns.color_palette("Spectral_r", 4).as_hex()))

# create data for E=0.1 Sigmoid/Golabi States
x = ['0.2', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0 \n (Linear model)']

states = np.c_[st_02, st_05, st_06, st_07, st_08, st_09, st_10]

# plot bars in stack manner
plt.figure(figsize=(6.5,14))
#y1
plt.bar(x, states[0], label = 'State 1', color= state_palette[0])
plt.bar(x, states[1], bottom=states[0], label = 'State 2', color= state_palette[1])
plt.bar(x, states[2], bottom=states[0]+states[1], label = 'State 3', color= state_palette[2])
plt.bar(x, states[3], bottom=states[0]+states[1]+states[2], label = 'State 4', color= state_palette[3])
plt.bar(x, states[4], bottom=states[0]+states[1]+states[2]+states[3], label = 'State 5', color= state_palette[4])
#y2
plt.bar(x, states[5], bottom= 1, color= state_palette[0])
plt.bar(x, states[6], bottom= 1+ states[5], color= state_palette[1])
plt.bar(x, states[7], bottom= 1+ states[5]+states[6], color= state_palette[2])
plt.bar(x, states[8], bottom= 1+ states[5]+states[6]+states[7], color= state_palette[3])
plt.bar(x, states[9], bottom= 1+ states[5]+states[6]+states[7]+states[8], color= state_palette[4])
#y3
plt.bar(x, states[10], bottom= 2, color= state_palette[0])
plt.bar(x, states[11], bottom= 2+ states[10], color= state_palette[1])
plt.bar(x, states[12], bottom= 2+ states[10]+states[11], color= state_palette[2])
plt.bar(x, states[13], bottom= 2+ states[10]+states[11]+states[12], color= state_palette[3])
plt.bar(x, states[14], bottom= 2+ states[10]+states[11]+states[12]+states[13], color= state_palette[4])
#y4
plt.bar(x, states[15], bottom= 3, color= state_palette[0])
plt.bar(x, states[16], bottom= 3+ states[15], color= state_palette[1])
plt.bar(x, states[17], bottom= 3+ states[15]+states[16], color= state_palette[2])
plt.bar(x, states[18], bottom= 3+ states[15]+states[16]+states[17], color= state_palette[3])
plt.bar(x, states[19], bottom= 3+ states[15]+states[16]+states[17]+states[18], color= state_palette[4])
#y5
plt.bar(x, states[20], bottom= 4, color= state_palette[0])
plt.bar(x, states[21], bottom= 4+ states[20], color= state_palette[1])
plt.bar(x, states[22], bottom= 4+ states[20]+states[21], color= state_palette[2])
plt.bar(x, states[23], bottom= 4+ states[20]+states[21]+states[22], color= state_palette[3])
plt.bar(x, states[24], bottom= 4+ states[20]+states[21]+states[22]+states[23], color= state_palette[4])

#y6
plt.bar(x, states[25], bottom= 5, color= state_palette[0])
plt.bar(x, states[26], bottom= 5+ states[25], color= state_palette[1])
plt.bar(x, states[27], bottom= 5+ states[25]+states[26], color= state_palette[2])
plt.bar(x, states[28], bottom= 5+ states[25]+states[26]+states[27], color= state_palette[3])
plt.bar(x, states[29], bottom= 5+ states[25]+states[26]+states[27]+states[28], color= state_palette[4])
#y7
plt.bar(x, states[30], bottom= 6, color= state_palette[0])
plt.bar(x, states[31], bottom= 6+ states[30], color= state_palette[1])
plt.bar(x, states[32], bottom= 6+ states[30]+states[31], color= state_palette[2])
plt.bar(x, states[33], bottom= 6+ states[30]+states[31]+states[32], color= state_palette[3])
plt.bar(x, states[34], bottom= 6+ states[30]+states[31]+states[32]+states[33], color= state_palette[4])
#y8
plt.bar(x, states[35], bottom= 7, color= state_palette[0])
plt.bar(x, states[36], bottom= 7+ states[35], color= state_palette[1])
plt.bar(x, states[37], bottom= 7+ states[35]+states[36], color= state_palette[2])
plt.bar(x, states[38], bottom= 7+ states[35]+states[36]+states[37], color= state_palette[3])
plt.bar(x, states[39], bottom= 7+ states[35]+states[36]+states[37]+states[38], color= state_palette[4])

plt.gca().invert_xaxis()
plt.legend(bbox_to_anchor=(0, 1.02, 1, 0.2), loc="lower left", mode="expand", borderaxespad=0, ncol=3)
plt.xlabel('Economies of scale parameter, b')
plt.ylabel('Fraction of states')
plt.axhline(y = 1, color = 'k', linestyle = '-')
plt.axhline(y = 2, color = 'k', linestyle = '-')
plt.axhline(y = 3, color = 'k', linestyle = '-')
plt.axhline(y = 4, color = 'k', linestyle = '-')
plt.axhline(y = 5, color = 'k', linestyle = '-')
plt.axhline(y = 6, color = 'k', linestyle = '-')
plt.axhline(y = 7, color = 'k', linestyle = '-')
plt.axhline(y = 8, color = 'k', linestyle = '-')
plt.ylim([0,8])

#plt.savefig('Transient_state_distribution_PWL.png', transparent=True, dpi = 144)
plt.show()

EDIT 1:

I created subplots but I cannot add 2nd Y axis on the other side. It requires to have fig, axs = plt.subplot() kind of definition.

Here's updated code.

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
state_palette = list((sns.color_palette("Spectral_r", 5).as_hex()))
action_palette = list((sns.color_palette("Spectral_r", 4).as_hex()))
# create data for E=0.1 Sigmoid/Golabi States
x = ['0.2', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0 \n (Linear model)']
states = np.c_[st_02, st_05, st_06, st_07, st_08, st_09, st_10]
actions = np.c_[act_02, act_05, act_06, act_07, act_08, act_09, act_10]
# plot bars in stack manner
plt.figure(figsize=(6,18))
plt.subplot(8, 1, 8)
#y1
plt.bar(x, states[0], label = 'State 1', color= state_palette[0])
plt.bar(x, states[1], bottom=states[0], label = 'State 2', color= state_palette[1])
plt.bar(x, states[2], bottom=states[0]+states[1], label = 'State 3', color= state_palette[2])
plt.bar(x, states[3], bottom=states[0]+states[1]+states[2], label = 'State 4', color= state_palette[3])
plt.bar(x, states[4], bottom=states[0]+states[1]+states[2]+states[3], label = 'State 5', color= state_palette[4])
plt.gca().invert_xaxis()
plt.ylim([0,1])
plt.yticks([0, 1])
plt.xlabel('Economies of scale parameter, b')
plt.subplot(8, 1, 7)
#y2
plt.bar(x, states[5], bottom= 0, color= state_palette[0])
plt.bar(x, states[6], bottom= 0+ states[5], color= state_palette[1])
plt.bar(x, states[7], bottom= 0+ states[5]+states[6], color= state_palette[2])
plt.bar(x, states[8], bottom= 0+ states[5]+states[6]+states[7], color= state_palette[3])
plt.bar(x, states[9], bottom= 0+ states[5]+states[6]+states[7]+states[8], color= state_palette[4])
plt.gca().invert_xaxis()
plt.ylim([0,1])
plt.xticks([])
plt.yticks([0, 1])
plt.subplot(8, 1, 6)
#y3
plt.bar(x, states[10], bottom= 0, color= state_palette[0])
plt.bar(x, states[11], bottom= 0+ states[10], color= state_palette[1])
plt.bar(x, states[12], bottom= 0+ states[10]+states[11], color= state_palette[2])
plt.bar(x, states[13], bottom= 0+ states[10]+states[11]+states[12], color= state_palette[3])
plt.bar(x, states[14], bottom= 0+ states[10]+states[11]+states[12]+states[13], color= state_palette[4])
plt.gca().invert_xaxis()
plt.ylim([0,1])
plt.xticks([])
plt.yticks([0, 1])
plt.subplot(8, 1, 5)
#y4
plt.bar(x, states[15], bottom= 0, color= state_palette[0])
plt.bar(x, states[16], bottom= 0+ states[15], color= state_palette[1])
plt.bar(x, states[17], bottom= 0+ states[15]+states[16], color= state_palette[2])
plt.bar(x, states[18], bottom= 0+ states[15]+states[16]+states[17], color= state_palette[3])
plt.bar(x, states[19], bottom= 0+ states[15]+states[16]+states[17]+states[18], color= state_palette[4])
plt.gca().invert_xaxis()
plt.ylim([0,1])
plt.xticks([])
plt.yticks([0, 1])
plt.subplot(8, 1, 4)
#y5
plt.bar(x, states[20], bottom= 0, color= state_palette[0])
plt.bar(x, states[21], bottom= 0+ states[20], color= state_palette[1])
plt.bar(x, states[22], bottom= 0+ states[20]+states[21], color= state_palette[2])
plt.bar(x, states[23], bottom= 0+ states[20]+states[21]+states[22], color= state_palette[3])
plt.bar(x, states[24], bottom= 0+ states[20]+states[21]+states[22]+states[23], color= state_palette[4])
plt.gca().invert_xaxis()
plt.ylim([0,1])
plt.xticks([])
plt.yticks([0, 1])
plt.subplot(8, 1, 3)
#y6
plt.bar(x, states[25], bottom= 0, color= state_palette[0])
plt.bar(x, states[26], bottom= 0+ states[25], color= state_palette[1])
plt.bar(x, states[27], bottom= 0+ states[25]+states[26], color= state_palette[2])
plt.bar(x, states[28], bottom= 0+ states[25]+states[26]+states[27], color= state_palette[3])
plt.bar(x, states[29], bottom= 0+ states[25]+states[26]+states[27]+states[28], color= state_palette[4])
plt.gca().invert_xaxis()
plt.ylim([0,1])
plt.xticks([])
plt.yticks([0, 1])
plt.subplot(8, 1, 2)
#y7
plt.bar(x, states[30], bottom= 0, color= state_palette[0])
plt.bar(x, states[31], bottom= 0+ states[30], color= state_palette[1])
plt.bar(x, states[32], bottom= 0+ states[30]+states[31], color= state_palette[2])
plt.bar(x, states[33], bottom= 0+ states[30]+states[31]+states[32], color= state_palette[3])
plt.bar(x, states[34], bottom= 0+ states[30]+states[31]+states[32]+states[33], color= state_palette[4])
plt.gca().invert_xaxis()
plt.ylim([0,1])
plt.xticks([])
plt.yticks([0, 1])
plt.subplot(8, 1, 1)
#y8
plt.bar(x, states[35], bottom= 0, color= state_palette[0], label = 'State 1')
plt.bar(x, states[36], bottom= 0+ states[35], color= state_palette[1], label = 'State 2')
plt.bar(x, states[37], bottom= 0+ states[35]+states[36], color= state_palette[2], label = 'State 3')
plt.bar(x, states[38], bottom= 0+ states[35]+states[36]+states[37], color= state_palette[3], label = 'State 4')
plt.bar(x, states[39], bottom= 0+ states[35]+states[36]+states[37]+states[38], color= state_palette[4], label = 'State 5')
plt.legend(bbox_to_anchor=(0, 1.02, 1, 0.2), loc="lower left", mode="expand", borderaxespad=0, ncol=3)
plt.gca().invert_xaxis()
plt.xticks([])
plt.ylim([0,1])
plt.yticks([0, 1])
plt.subplots_adjust(wspace=0, hspace=0.175)
plt.tick_params(labelcolor="none", bottom=False, left=False)
#plt.savefig('Transient_state_distribution_PWL.png', transparent=True, dpi = 144)
plt.show()

答案1

得分: 1

  • 我认为如果使用pandas,代码会更简洁且易于阅读。

    • pandas.DataFrme.plot API在绘制分组或堆叠条形图时效率更高。
    • 不包括数据数组,原始代码中有大约105行代码。使用pandas选项可将其减少到36行代码(不包括空格),更容易扩展。
  • 对于标签:

    • 使用fig标签
      • fig.supxlabel
      • fig.supylabel
      • fig.suptitle
    • 根据原始代码,使用ax = plt.gca()ax_right = ax.twinx(),然后使用ax_right.set_ylabel(...)
    • 使用以下代码可以在右侧y轴上绘制:ax.yaxis.set_label_position('right')
    • .set_ylabel具有labelpad参数来更改位置以适应坐标轴边界框。
  • 请参考Matplotlib应用接口(APIs)

  • python 3.11.2pandas 2.0.1matplotlib 3.7.1中测试通过

英文:
  • I think the code will be more concise, and easier to read if pandas is used.
    • The pandas.DataFrme.plot API is much more efficient at plotting grouped or stacked bars.
    • Not including the arrays for the data, there are currently about 105 lines of code in the OP. Using the pandas option reduces that to 36 lines of code (not including blank spaces), which scales more easily.
  • For labels:
    • Use fig labels
      • fig.supxlabel
      • fig.supylabel
      • fig.suptitle
    • Given the code in the OP, use ax = plt.gca() and ax_right = ax.twinx(), and then ax_right.set_ylabel(...).
    • With the following code you plot on the right y-axis with ax.yaxis.set_label_position('right')
    • .set_ylabel has the labelpad parameter the change the position from the Axes bounding box.
  • Please refer to the Matplotlib Application Interfaces (APIs)
    • If you are creating one plot (no subplots), then it's okay to use the implicit "pyplot" interface, otherwise you should use the explicit "Axes" interface.
    • It is bad practice to switch between explicit and implicit commands, though there are many answers doing so.
  • Tested in python 3.11.2, pandas 2.0.1, matplotlib 3.7.1
import pandas as pd
import matplotlib.pyplot as plt

# stack the data
states = np.c_[st_02, st_05, st_06, st_07, st_08, st_09, st_10]

# create a dataframe from states
df_st = pd.DataFrame(states)

# split the dataframe into 5 row chunks
n = 5
list_st = [df_st[i:i+n].reset_index(drop=True) for i in range(0, df_st.shape[0], n)]

state_palette = list((sns.color_palette("Spectral_r", 5).as_hex()))

# create the figure and axes
fig, axes = plt.subplots(nrows=len(list_st), figsize=(6, 18), sharex=True, gridspec_kw={'hspace': 0.1, 'wspace': 0})

# reverse the axes based on the preferred display options
axes = axes[::-1]

# years labels
years = range(2015, 2024)

# iterate through each axes and it's associated data
for ax, data, year in zip(axes, list_st, years):
    
    # transpose the dataframe and then reverse the column order
    data = data.T[::-1]
    
    # set the index labels (e.g. the x-axis)
    data.index = ['1.0 \n (Linear model)', '0.9', '0.8', '0.7', '0.6', '0.5', '0.2']
    
    # set the column names (e.g. the legend labels)
    data.columns = [f'State {i}' for i in range(1, 6)]
    
    # plot the data on the axes
    data.plot(kind='bar', stacked=True, ax=ax, legend=False, width=0.85, ec='k', rot=0, yticks=[0, 1], color=state_palette)
    
    # right y-axis label
    ax.yaxis.set_label_position('right')
    ax.set_ylabel(f'Year: {year}', rotation=-90, labelpad=15)
    
    # remove x-ticks on all but the bottom axes
    if ax != axes[0]:
        ax.tick_params(bottom=False)

    # create a legend for the top axes
    if ax == axes[-1]:
        ax.legend(bbox_to_anchor=(0, 1.02, 1, 0.2), loc='lower left', mode='expand', borderaxespad=0, ncol=3)

fig.supxlabel('Economies of scale parameter, b', y=0.06)
fig.supylabel('Fractions of States')
fig.suptitle('The Figure Title', y=0.93)

在轴值之间放置标签并添加第二个Y轴


  • Using ax.twinx
...

    # plot the data on the axes
    data.plot(kind='bar', stacked=True, ax=ax, legend=False, width=0.85, ec='k', rot=0, yticks=[0, 1], color=state_palette)

    # remove ax.yaxis.set_label_position('right')
    # remove ax.set_ylabel(f'Year: {year}', rotation=-90, labelpad=15)
    
    # set the left y-axis label
    ax.set_ylabel('Range', labelpad=0)
    
    # using twinx to add a right y-axis label
    ax_right = ax.twinx()
    ax_right.set_ylabel(f'Year: {year}', rotation=-90, labelpad=15)
    ax_right.set_yticks([], [])  # remove the right yticks and yticklabels

...

在轴值之间放置标签并添加第二个Y轴

huangapple
  • 本文由 发表于 2023年5月21日 22:22:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76300372.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定