在 pandas 中绘制数据和图形文本

Plotting of data and figure text in pandas

我正在使用数据框

df = pd.DataFrame({"Region": [1,2,3,4,5,6,7,8,9,10], "mean_w_em": [1261011,4144337.50,8457283.00,46182432.13,22421525.98,29881120.90,5111470.52,5986791.17,3262314.22, 4192573.09],"rate":[.02,.06,.16,.24,.21,.19,.02,.03,.04,.0]})

我使用以下代码:

ax = aa.plot(kind = 'bar', x = 'Region',
                  y = 'HPV Rate', color = 'silver',
                  linewidth = 3,figsize = (15,8))
 
ax2 = aa.plot(kind = 'line', x = 'Region',
                   y = 'Mean Weighted Emissions', secondary_y = True,
                   color='blue',marker='.',  linewidth = 0.75,
                   ax = ax)
 
#title of the plot
plt.title("HPV rate and Weighted Air Emissions by Region")
 
#labeling x and y-axis
ax.set_xlabel('Region')
ax.set_ylabel('HPV Rate')
ax2.set_ylabel('Mean Weighted Emissions')
 
#defining display layout
plt.tight_layout()
plt.figtext(0.5, 0.01, "Region 1:CT,ME,MA,NH,RI,VT Region 2:NJ,NY,PR,VI",ha="center", fontsize = 10,bbox={"facecolor":"orange", "alpha":0.6, "pad":5})
#show plot
plt.show()


我得到了以下情节

我的问题:

  1. 如何绘制第二个 y 轴而不是 le7 的完整值?
  2. 如何避免绘图文本与标签重叠?
  3. 我想按以下方式添加剧情文本解释,而不是并排。我该怎么做?

你可以用get_major_formatter().set_scientific(False)去掉科学记数法,你可以把图形文本放到x标签里,也可以使用参数in_layout = False。我包含了 x 标签的注释代码,这样您就可以看到它是如何在那里使用的。创建换行符的关键是 \n.

import pandas as pd
import matplotlib.pyplot as plt


aa = pd.DataFrame({"Region": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'Mean Weighted Emissions': [1261011, 4144337.50, 8457283.00, 46182432.13, 22421525.98,
                  29881120.90, 5111470.52, 5986791.17, 3262314.22, 4192573.09], 'HPV Rate': [.02, .06, .16, .24, .21, .19, .02, .03, .04, .0]})


ax = aa.plot(kind = 'bar', x = 'Region',
             y = 'HPV Rate', color = 'silver',
             linewidth = 3, figsize = (15, 8))

ax2 = aa.plot(kind='line', x='Region',
              y='Mean Weighted Emissions', secondary_y = True,
              color='blue', marker='.',  linewidth=0.75,
              ax=ax)

# title of the plot
plt.title("HPV rate and Weighted Air Emissions by Region")

# labeling x and y-axis
# ax.set_xlabel('Region\n\nRegion 1:CT,ME,MA,NH,RI,VT\nRegion 2:NJ,NY,PR,VI\n\n')
ax.set_xlabel('Region')
ax.set_ylabel('HPV Rate')
ax2.set_ylabel('Mean Weighted Emissions')

# change notation
ax2.yaxis.get_major_formatter().set_scientific(False)

# add text
ax.text(1, 1, "Region\n1: and your states\n2: more states", fontsize = 12)

# defining display layout
plt.tight_layout()
plt.figtext(0.5, 0.01, "Region 1:CT,ME,MA,NH,RI,VT\nRegion 2:NJ,NY,PR,VI",
            in_layout = False,
            ha="center", fontsize=10, bbox={"facecolor": "orange", "alpha": 0.6, "pad": 3})
# show plot
plt.show()