简体   繁体   中英

How to label the line with the values in y-axis?

在此处输入图片说明

    # -*- coding: utf-8 -*-
"""
Created on Sun Oct 28 17:35:48 2018

@author: User
"""

import matplotlib
matplotlib.use('GTKAgg')

import matplotlib.pyplot as plt
import matplotlib.transforms
import numpy as np
from sklearn.linear_model import LinearRegression
import pandas


# Load CSV and columns
df = pandas.read_csv(r'C:\Users\User\Desktop\dataset.csv')
print (df.head())

df = df[['TTL_value','packet_size']]

#X = df['Input_port']
#Y = df['Output_port']


X=np.array(df.packet_size)
Y=np.array(df.TTL_value)

#Split the data into training/testing sets
X_train = X[:-100]
X_test = X[-100:]

# Split the targets into training/testing sets
Y_train = Y[:-100]
Y_test = Y[-100:]

# Plot outputsregr = linear_model.LinearRegression()
regr=LinearRegression(fit_intercept=True)
regr.fit(X_test[:,np.newaxis],Y_test)

X_testfit=np.linspace(0,100000)
Y_testfit=np.linspace(255,255)
#Y_testfit=regr.predict(X_testfit[:,np.newaxis])
print ("Normal Pakctet size range is 7 to 65542")
plt.scatter(X_test, Y_test,  color='black')
plt.plot(X_testfit, Y_testfit,  color='red',linewidth=3)
plt.title('Test Data')
plt.xlabel('packet_size')
plt.ylabel('TTL_value')
plt.xticks((0,20000,40000,60000,80000,100000))
plt.yticks((0,50,100,150,200,250,300))

plt.show()
print ("The TTL value more than 255 is a malicious traffic")

I want to display the red line with the values of the y-axis.The red line is at 255. I tried many times, but really couldn't do it.

If I understood you correctly, you want to annotate the red horizontal line at y=255 with the corresponding y-value (255). In that case, here is a sample working solution for you. You just need to use plt.text with the desired x- and y-coordinates and the string you want to put as the text. Here I am using the y-value as the string. Y_testfit[0]*1.005 slightly shifts the text above the horizontal line to avoid overlap with it.

You can adapt this solution for your problem.

import matplotlib.pyplot as plt

X_testfit=np.linspace(0,100000)
Y_testfit=np.linspace(255,255)

plt.plot(X_testfit, Y_testfit, '-r', lw=3)
plt.text(20000, Y_testfit[0]*1.005, 'y=%d' %Y_testfit[0], fontsize=20)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM