如何在matplotlib中更改x和y轴?

2024-05-20 15:47:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我用matplotlib绘制神经网络。我发现了一个绘制神经网络的代码,但它是自上而下的。我想把方位从左改到右。所以基本上我想改变x和y轴后,我已经绘制了所有的形状。有什么简单的方法可以做到这一点吗? 我还找到了一个答案,上面说可以将参数“orientation”更改为horizontal(下面的代码),但我不太明白应该在代码中的什么地方复制它。这能给我同样的结果吗?

matplotlib.pyplot.hist(x, 
                   bins=10, 
                   range=None, 
                   normed=False, 
                   weights=None, 
                   cumulative=False, 
                   bottom=None, 
                   histtype=u'bar', 
                   align=u'mid', 
                   orientation=u'vertical', 
                   rwidth=None, 
                   log=False, 
                   color=None, 
                   label=None, 
                   stacked=False, 
                   hold=None, 
                   **kwargs)

Tags: 方法答案代码nonefalse参数matplotlib地方
1条回答
网友
1楼 · 发布于 2024-05-20 15:47:02

代码中的内容是如何在matplotlib中启动直方图的示例。注意,您使用的是pyplot默认接口(不一定要构建自己的图形)。

因此这一行:

orientation=u'vertical',

应该是:

orientation=u'horizontal',

,如果你想让酒吧从左到右。但这对y轴没有帮助。要反转y轴,应使用以下命令:

plt.gca().invert_yaxis()

下面的例子向您展示了如何从随机数据中构建直方图(非对称以便更容易感知修改)。第一个图是标准直方图,第二个图改变了直方图的方向;最后一个图反转了y轴。

import numpy as np
import matplotlib.pyplot as plt

data = np.random.exponential(1, 100)

# Showing the first plot.
plt.hist(data, bins=10)
plt.show()

# Cleaning the plot (useful if you want to draw new shapes without closing the figure
# but quite useless for this particular example. I put it here as an example).
plt.gcf().clear()

# Showing the plot with horizontal orientation
plt.hist(data, bins=10, orientation='horizontal')
plt.show()

# Cleaning the plot.
plt.gcf().clear()

# Showing the third plot with orizontal orientation and inverted y axis.
plt.hist(data, bins=10, orientation='horizontal')
plt.gca().invert_yaxis()
plt.show()

图1的结果是(默认直方图):

default histogram in matplotlib

第二个(更改了条形图方向):

default histogram in matplotlib with changed orientation

最后是第三个(y轴倒转):

Histogram in matplotlib with horizontal bars and inverted y axis

相关问题 更多 >