Pandas barh绘图首条条形图显示不全问题求助
问题
使用以下代码基于Pandas DataFrame生成双轴水平条形图(barh)时,名称K对应的首条条形图无法完整显示,请问如何添加边距调整轴与绘图区域的间距?
fig = plt.figure(figsize = (10, 6)) ax = fig.add_subplot() ax2 = ax.twiny() import matplotlib.pyplot as plt import numpy as np import pandas as pd from io import StringIO s = StringIO("""name amount price A 40929 4066443 B 93904 9611272 C 188349 19360005 D 248438 24335536 E 205622 18888604 F 140173 12580900 G 76243 6751731 H 36859 3418329 I 29304 2758928 J 39768 3201269 K 30350 2867059""") df = pd.read_csv(s, delimiter=' ', skipinitialspace=True) df.plot(x = 'name', y = 'price', kind = 'barh', ax = ax, color = 'steelblue', width = 0.4, position = 0) df.plot(x = 'name', y = 'amount', kind = 'barh', ax = ax2, color = 'salmon', width = 0.4, position = 1)
绘图时K对应的条形图左侧被截断,无法完整显示。
解决方案
方法1:调整绘图区域边距
在代码末尾添加plt.subplots_adjust(left=0.1),直接调整整个图表的左侧边距,给条形图留出足够空间:
import matplotlib.pyplot as plt import numpy as np import pandas as pd from io import StringIO # 规范代码顺序,先导入库 fig = plt.figure(figsize = (10, 6)) ax = fig.add_subplot() ax2 = ax.twiny() s = StringIO("""name amount price A 40929 4066443 B 93904 9611272 C 188349 19360005 D 248438 24335536 E 205622 18888604 F 140173 12580900 G 76243 6751731 H 36859 3418329 I 29304 2758928 J 39768 3201269 K 30350 2867059""") df = pd.read_csv(s, delimiter=' ', skipinitialspace=True) df.plot(x = 'name', y = 'price', kind = 'barh', ax = ax, color = 'steelblue', width = 0.4, position = 0) df.plot(x = 'name', y = 'amount', kind = 'barh', ax = ax2, color = 'salmon', width = 0.4, position = 1) # 调整左侧边距,数值可根据需求修改 plt.subplots_adjust(left=0.1) plt.show()
方法2:设置轴的边距
通过ax.margins()和ax2.margins()给两个轴添加x方向的边距,确保条形图完整显示:
import matplotlib.pyplot as plt import numpy as np import pandas as pd from io import StringIO fig = plt.figure(figsize = (10, 6)) ax = fig.add_subplot() ax2 = ax.twiny() s = StringIO("""name amount price A 40929 4066443 B 93904 9611272 C 188349 19360005 D 248438 24335536 E 205622 18888604 F 140173 12580900 G 76243 6751731 H 36859 3418329 I 29304 2758928 J 39768 3201269 K 30350 2867059""") df = pd.read_csv(s, delimiter=' ', skipinitialspace=True) df.plot(x = 'name', y = 'price', kind = 'barh', ax = ax, color = 'steelblue', width = 0.4, position = 0) df.plot(x = 'name', y = 'amount', kind = 'barh', ax = ax2, color = 'salmon', width = 0.4, position = 1) # 给两个x轴添加边距,x参数控制水平方向边距比例 ax.margins(x=0.05) ax2.margins(x=0.05) plt.show()
额外优化
原代码将库导入语句放在创建图表之后,建议调整到代码开头,符合Python代码规范。
内容的提问来源于stack exchange,提问作者ahajib
相关产品推荐
相关产品推荐

