我正在尝试创建一个图,该图的底部有一个x轴,带有基于文本的标签,而我想在顶部有另一个x轴,具有不同的基于文本的标签。
到目前为止,我发现最接近的东西是“ secondary_axis”(Link),但是当我尝试填充基于文本的标签时,会出现TypeError: unhashable type: numpy.ndarray
。
我根据this的一些代码制作了以下示例:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# sphinx_gallery_thumbnail_number = 2
vegetables = ["cucumber", "tomato", "lettuce", "asparagus",
"potato", "wheat", "barley"]
farmers = ["Farmer Joe", "Upland Bros.", "Smith Gardening",
"Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."]
vegetables_to_farmers = dict(zip(vegetables, farmers))
farmers_to_vegetables = dict(zip(farmers, vegetables))
harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],
[2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],
[1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],
[0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],
[0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],
[1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],
[0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])
fig, ax = plt.subplots()
im = ax.imshow(harvest)
# We want to show all ticks...
ax.set_xticks(np.arange(len(farmers)))
ax.set_yticks(np.arange(len(vegetables)))
# ... and label them with the respective list entries
ax.set_xticklabels(farmers)
# Rotate the tick labels and set their alignment.
plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
rotation_mode="anchor")
def vegetables2farmers(x):
return vegetables_to_farmers[x]
def farmers2vegetables(x):
return farmers_to_vegetables[x]
secax = ax.secondary_xaxis('top', functions=(vegetables2farmers, farmers2vegetables))
fig.tight_layout()
plt.show()
最好在顶部栏中显示蔬菜作为标签。你有办法解决这个问题吗?
答案 0 :(得分:2)
您正在将轴刻度的概念与轴标签混合在一起。 modules = [14, 1969, 100756]
def getfuel(lst):
result = 0
while lst:
lst = [x for x in [x // 3 - 2 for x in lst] if x > 0]
result+=sum(lst)
return result
print(getfuel(modules)) # returns the sum
的函数及其逆函数用于转换坐标,而不是标签。
原则上,如果允许设置不同的格式化程序,则使用辅助轴会更好。不幸的是,到目前为止,情况并非如此。
另一种选择是使用双轴。但这不适用于具有相同长宽比的轴。
因此,作为最后的手段,您可以在旧轴的顶部创建一个新轴并对其进行统一格式化:
secondary_axis