简体   繁体   中英

How can I increase range of x-axis in probability density plot even If I have no data for that?

Actually I am trying to plot density plot in python. I want range for -1 to 1 however I know I don't have values in my data set beyond -0.6 and 0.6. But is there any way where I can plot just zero for all the values beyond -0.6 an 0.6. In short I want to increase range of my plot to make it consistent.

在此处输入图像描述

So far I am using this code:

import pandas as pd
import matplotlib.pyplot as plt
#import seaborn as sns

data_Pre1 = pd.read_csv("new errors.csv")


for s in data_Pre1.columns:
    data_Pre1[s].plot(kind='density', sharey = True)
#plt.title("Disk Galaxies", fontsize = 18)
plt.xlabel("$E_i$", fontsize = 40)
plt.ylabel('Density', fontsize = 40)
plt.xlim(-1,1)
plt.legend(fontsize =25)
plt.xticks(size = 15)
plt.yticks(size = 15)
plt.show()

My solution is based on passing ind parameter to plot . It specifies evaluation points for the estimated PDF. As the number of points I chose 700 but you can change it as you wish, eg to get more smooth curves. For consistency, pass just the same border values to plt.xlim(...) .

So change respective lines of your code to:

minX, maxX = (-1.0, 1.0)
for s in data_Pre1.columns:
    data_Pre1[s].plot(kind='density', sharey=True, ind=np.linspace(minX, maxX, 700))
plt.xlim(minX, maxX)

Other possible correction is that instead of explicit looping over columns of your DataFrame, you can call your plot for the whole DataFrame:

data_Pre1.plot.density(ind=np.linspace(minX, maxX, 700))

Edit

The evaluation points specified with ind need not be evenly spaced throughout the whole x axis "wanted" range.

If you are sure about both "limits" of x axis "discovered" by the plotting function (you wrote -0.6 and 0.6 ), you can generate ind as densely spaced points only in this range and then:

  • prepend it with a single point - your "wanted" lower x limit,
  • append it with also a single point - your "wanted" upper x limit.

So you can change your code to:

minX, maxX = (-1.0, 1.0)      # "Wanted" x axis limits
minSrc, maxSrc = (-0.6, 0.6)  # X axis limits "discovered" in your data
nPoints = 700                 # How many estimation points in the "discovered" range
ind = np.concatenate(([minX], np.linspace(minSrc, maxSrc, nPoints), [maxX]))
data_Pre1.plot.density(ind=ind)
plt.xlim(minX, maxX)

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