【问题标题】:'numpy.ndarray' object has no attribute 'set_xlabel'“numpy.ndarray”对象没有属性“set_xlabel”
【发布时间】:2020-12-21 17:43:38
【问题描述】:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

#reading data
data = pd.read_csv('Malicious_or_criminal_attacks_breakdown-Top_five_industry_sectors_July-Dec-2019.csv',index_col=0,engine='python')
df = pd.DataFrame(data)


#df list for data
df.values.tolist()

#construction of group bar chart
labels = ('Cyber incident', 'Theft of paperwork or data storagedevice', 'Rogue employee', 'Social engineering / impersonation')
colors = ['red', 'yellow', 'blue', 'green']
data = df.values.tolist()
arr = np.array(data)


n_groups, n_colors = arr.shape
width = 0.2
x_pos = np.arange(n_colors)

fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(14, 5), dpi=100)
for i in range(n_groups):
    plt.bar(x_pos + i*width, arr[i, :], width, align='center', label=labels[i], color=colors[i])
ax.set_xlabel("the top five industry sectors")
ax.set_ylabel("Number of attack")
ax.set_title("Type of attack by top five industry sectors")

ax.set_xticks(x_pos+width/2)
ax.set_xticklabels(colors)

ax.legend()

谁能告诉我我在这里做错了什么以及为什么 numpy 没有按预期工作。我看了几个小时的文档,无法弄清楚什么是错的

【问题讨论】:

  • ax 是子图的ndarray

标签: python-3.x numpy matplotlib


【解决方案1】:

Ax 是一组子图,因为您创建了多个子图。因此,为了设置子图的标题,您还需要遍历它们。你可以像这样很容易地解决这个问题:

fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(14, 5), dpi=100)
for i in range(n_groups):
    plt.bar(x_pos + i*width, arr[i, :], width, align='center', label=labels[i], color=colors[i])

for subplot in ax:
    subplot.set_xlabel("the top five industry sectors")
    subplot.set_ylabel("Number of attack")
    subplot.set_title("Type of attack by top five industry sectors")

    subplot.set_xticks(x_pos+width/2)
    subplot.set_xticklabels(colors)
    
    subplot.legend()

如果你想为不同的子图设置不同的标题和内容,你需要进行调整。

【讨论】:

  • 它会抛出一个错误“索引 2 超出了轴 0 大小为 2 的范围”
  • 那是因为我假设 n_groups 是 2。在这种情况下,您需要分离循环。我相应地编辑了代码。
  • 谢谢你,这有助于我更好地理解它
猜你喜欢
  • 2020-09-22
  • 2020-02-21
  • 2020-12-08
  • 2019-12-10
  • 2017-07-10
  • 2020-05-10
  • 2019-11-04
  • 2017-05-24
  • 2021-06-14
相关资源
最近更新 更多