Matplotlib scatterplot error bars two data sets

假如想象 提交于 2019-12-14 04:23:14

问题


I have two data sets, which I'd like to scatter plot next to each other with error bars. Below is my code to plot one data set with error bars. And also the code to generate the second data set. I'd like the points and errors for each data for each value to be adjacent.

I'd also like to remove the line connecting the dots.

import random
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as ss

data = []
n = 100
m = 10

for i in xrange(m):
    d = []
    for j in xrange(n):
        d.append(random.random())
    data.append(d)

mean_data = []
std_data = []

for i in xrange(m):
    mean = np.mean(data[i])
    mean_data.append(mean)
    std = np.std(data[i])
    std_data.append(std)



df_data = [n] * m
plt.errorbar(range(m), mean_data, yerr=ss.t.ppf(0.95, df_data)*std_data)
plt.scatter(range(m), mean_data)
plt.show()


new_data = []


for i in xrange(m):
    d = []
    for j in xrange(n):
        d.append(random.random())
    new_data.append(d)


mean_new_data = []
std_new_data = []

for i in xrange(m):
    mean = np.mean(new_data[i])
    mean_new_data.append(mean)
    std = np.std(new_data[i])
    std_new_data.append(std)



df_new_data = [n] * m


回答1:


To remove the line in the scatter plot use the fmt argument in plt.errorbar(). The plt.scatter() call is then no longer needed. To plot a second set of data, simply call plt.errorbar() a second time, with the new data.

If you don't want the datasets to overlap, you can add some small random scatter in x to the new dataset. You can do this in two ways, add a single scatter float with

random.uniform(-x_scatter, x_scatter)

which will move all the points as one:

or generate a random scatter float for each point with

x_scatter = np.random.uniform(-.5, .5, m)

which generates something like

To plot both datasets (using the second method), you can use:

plt.errorbar(
    range(m), mean_data, yerr=ss.t.ppf(0.95, df_data)*std_data, fmt='o',
    label="Data")
# Add some some random scatter in x
x_scatter = np.random.uniform(-.5, .5, m)
plt.errorbar(
    np.arange(m) + x_scatter, mean_new_data,
    yerr=ss.t.ppf(0.95, df_new_data)*std_new_data, fmt='o', label="New data")
plt.legend()
plt.show()


来源:https://stackoverflow.com/questions/43838665/matplotlib-scatterplot-error-bars-two-data-sets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!