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

时间:2016-08-19 22:40:06

标签: python matplotlib

我使用matplotlib来绘制神经网络。我发现了一个绘制神经网络的代码,但它是从上到下的方向。我想从左到右改变方向。所以基本上我想在绘制完所有形状后改变x和y轴。是否有捷径可寻? 我还找到了一个答案,说你可以改变参数" orientation"横向(下面的代码),但我真的不明白我的代码应该在哪里复制它。会给我同样的结果吗?

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)

1 个答案:

答案 0 :(得分:4)

您的代码中包含的是如何在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