Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 修改覆盖matplotlib的轴和标签_Python_Matplotlib_Graph_Seaborn - Fatal编程技术网

Python 修改覆盖matplotlib的轴和标签

Python 修改覆盖matplotlib的轴和标签,python,matplotlib,graph,seaborn,Python,Matplotlib,Graph,Seaborn,我在格式化seaborn图形时遇到问题,我在其中叠加了两个图形(直线和条形)。假设到目前为止我有以下代码: fig, ax1 = plt.subplots() ax2 = ax1.twinx() df1["a"].plot(kind='bar', color='blue', ax=ax1) df2["b"].plot(kind='line', marker='d', ax=ax2) ax.set_xticklabels(('2015', '2016', '

我在格式化seaborn图形时遇到问题,我在其中叠加了两个图形(直线和条形)。假设到目前为止我有以下代码:

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
df1["a"].plot(kind='bar', color='blue', ax=ax1)
df2["b"].plot(kind='line', marker='d', ax=ax2)
ax.set_xticklabels(('2015', '2016', '2017', '2018', '2019', '2020'))
ax1.yaxis.tick_right()
ax1.set_ylabel('Label A')
ax2.yaxis.tick_left()
ax2.set_ylabel('Label B')
ax1.set_xticklabels(('2015', '2016', '2017', '2018', '2019', '2020'))
plt.show()
产生了这样的东西:

如果我能得到以下方面的建议,我将不胜感激:

  • 避免标签和记号重叠
  • 将标签B轴设置为0~100之间的百分比(是的,我的大部分数据都在30%左右,但我想指出它有多低)。基本上,我想尝试axes.ylim((“0”,“100”)),但它对我不起作用
  • 显示每根钢筋的整个宽度(第一根和最后一根钢筋被轴切割,但我真的不知道如何避免)
非常抱歉,如果我在这里犯了一些基本的错误,但这将非常有帮助,因为在我的在线课程中,似乎没有人积极参与查询

*编辑: 请注意,我的屏幕截图在其中一个y轴上有非常大的数字,因为我刚刚拍摄了我的实际工作笔记本。但是,请随意使用以下示例数据集进行演示:

df1 =  [39, 30, 40, 36, 28, 42]
df2 = [5, 8, 7, 3, 2, 6]

让我们尝试用代码解决您的问题:

from matplotlib import ticker

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()

# don't try to force tick left/right. Swap the axes
df1["a"].plot(kind='bar', color='blue', ax=ax2)
df2["b"].plot(kind='line', marker='d', ax=ax1)
ax1.set_xticklabels(('2015', '2016', '2017', '2018', '2019', '2020'))

# disable these
# ax1.yaxis.tick_right()
# ax2.yaxis.tick_left()

# format to percentage
ax2.yaxis.set_major_formatter(ticker.StrMethodFormatter("{x}%"))

ax1.set_ylabel('Label B')
ax2.set_ylabel('Label A')

fig.tight_layout()
plt.show()
你会得到这样的结果:


我还担心左上角的1e11,这意味着y轴上的“8”不是
8
,而是
8000000000
。这就是你想要的吗?如果您能提供一个最小但显示了这些相同问题且我们可以运行的,那将是最好的(只需为它制作一些虚假数据,如
data1=[4,3,7,7,2,6]
或其他)。感谢您指出这一点。我正在编写的实际代码(我截图的地方)有大量的总预算。(稍后我可能会将它们清理成xx百万/千的形式…)但是的,我可能会放置一个随机样本数据框以防万一!非常感谢你在这里帮助我。我能够像我所希望的那样对齐轴和x轴标记的标签!如果可能的话,我还想知道如何将y轴(百分比)也缩小(即0%~100%)。我尝试设置y-lim(“0”、“100”),但ax似乎没有该属性:(