簡體   English   中英

如何 plot 在 x 軸上有 2 個變量並在 y 軸上計數的圖形?

[英]How to plot a graph with 2 variables on the x axis and count on the y axis?

我正在嘗試 plot 一個圖表來顯示授權和未授權的不同 IP 地址嘗試的數量。 我擁有的數據看起來像這樣:

    Access Type     host/IP address Count
0   Authorized      206.196.21.129  23
1   Authorized      207.30.238.8    46
2   Authorized      208.62.55.75    23
3   Authorized      216.12.111.241  23
4   Authorized      63.197.98.106   23
5   Authorized      67.95.49.172    23
6   Unauthorized    207.243.167.114 23
7   Unauthorized    209.152.168.249 10
8   Unauthorized    65.166.159.14   10
9   Unauthorized    68.143.156.89   10

我該怎么做呢? 我在想 X 軸將有 IP 地址作為主要 header 和訪問類型的計數作為子 header。

你可以做這樣的事情; 在下面的代碼中,我將“未授權”IP 着色為紅色,將“授權”IP 着色為綠色。 你可以改變它。

import pandas as pd
import matplotlib.pyplot as plt


# df has data
colors = ['r' if item == "Unauthorized" else 'g' for item in df["Access Type"]]
df.plot(kind='bar', x='host/IP address', y='Count', color=colors, legend=False)
plt.show()

產生類似的東西: 在此處輸入圖像描述

這是 Python 中一種非常優雅的方式

import numpy as np
import pandas as pd
from plotnine import *
%matplotlib inline
df = pd.read_csv('~/Downloads/Untitled spreadsheet - Sheet1.csv')
ggplot(df, aes(x='Access Type', y = "Count" ,fill = 'host address'))+ 
geom_bar(stat="identity",position="dodge")

IP 地址作為顏色

如果您沒有 plotnine,請使用

pip install plotnine

如果您對此感興趣,這是另一種形式的着色。

ggplot(df, aes(x='host address', y = "Count" ,fill = 'Access Type'))+ 
geom_bar(stat="identity",position="dodge")+ 
theme(axis_text_x=element_text(angle=45))

在此處輸入圖像描述

我參加聚會有點晚了。 由於已經有一些條形圖顯示為解決方案,您如何看待使用氣泡 plot?

在此處輸入圖像描述

# Visualizing 4-D mix data using bubble plots

#create custom legend
red_patch = mpatches.Patch(color='red', label='Unauthorized Access', alpha=0.4)
blue_patch = mpatches.Patch(color='blue', label='Authorized Access', alpha=0.4)

#specify figure size
plt.figure(figsize=(7,7))

#specify blubble size
size = df['Count']*25

#define fill and edge colors
fill_colors = ['red' if access_type=='Unauthorized' else 'blue' for access_type in 
list(df['Access Type'])]
edge_colors = ['red' if access_type=='red' else 'blue' for access_type in list(df['Access Type'])]

#create scatter plot
plt.scatter(df['host/IP address'], df['Count'], s=size, 
            alpha=0.4, color=fill_colors, edgecolors="black",)

#rotate axis titles, IP Adress will not fit on the axis without rotation
plt.xticks(rotation=90)

#set legend handles
plt.legend(handles=[red_patch, blue_patch])

# give y and x axis titles and plot title
plt.xlabel('Host/IP Address')
plt.ylabel('Access Type Counts')
[![enter image description here][1]][1]plt.title('Access Type Counts by Host/IP Address',y=1.05)

您只是在這里提供示例數據,對嗎? 一個 IP 地址是否會發生未經授權和授權訪問? 確保您的 plot 能夠應對此類情況。

本文就如何可視化分類變量提供了很好的想法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM