简体   繁体   English

如何使 x_labels 出现在彼此的子图上?

[英]How to make the x_labels appear for subplots that are on each other?

I'm learning how to create a dashboard to track my expenses.我正在学习如何创建仪表板来跟踪我的开支。 The first goal is to create a simple bar-plot that tracks my income and expenses for the two biggest categories.第一个目标是创建一个简单的条形图来跟踪我的两个最大类别的收入和支出。 The code for the bar-plot is supplied below.下面提供了条形图的代码。

income = 5000
immediate_obligations = -1000
true_expenses = -2000
total = income - immediate_obligations - true_expenses

fig,ax = plt.subplots()
ax.bar(x=[1],height=[income],color = 'green',tick_label="Income")
ax.bar(x=[2,3],height=[immediate_obligations,true_expenses], color = 'red', tick_label=["Immediate Obligations","true_expenses"])
ax.bar(x=[4],height=[total], color = 'blue')

fig.suptitle('Spending Current Month')

The reason I went for three axes was to be able to color the income green, the expenses red, and the difference blue.我选择三轴的原因是能够将收入涂成绿色,支出涂成红色,差额涂成蓝色。 The plots render well because they don't overlap.这些图渲染得很好,因为它们不重叠。 However the tick_labels only appear for the plot that is created the latest.但是,tick_labels 仅针对最新创建的 plot 出现。 It makes sense, but how do I apply the labels to the entire plot?这是有道理的,但是如何将标签应用于整个 plot?

在此处输入图像描述

The argument color does not have to be a single color .参数color 不必是单一颜色 You can pass an array with the color of each bar.您可以传递一个包含每个条形颜色的数组。 Therefore your output can be a achieved using only one call to bar() :因此,您的 output 只需一次调用bar()即可实现:

income = 5000
immediate_obligations = -1000
true_expenses = -2000
total = income - immediate_obligations - true_expenses

bars = [income, immediate_obligations, true_expenses, total]
colors = ['g','r','r','b']
labels = ['Income','Immediate obligations','True expenses','Total']

fig,ax = plt.subplots()
ax.bar(x=range(len(bars)), height=bars, color=colors, tick_label=labels)
fig.suptitle('Spending Current Month')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM