Python Matplotlib Box Plot Two Data Sets Side by Side

2024/10/9 2:27:30

I would like to make a boxplot using two data sets. Each set is a list of floats. A and B are examples of the two data sets

A = []
B = []for i in xrange(10):l = [random.random() for i in xrange(100)]m = [random.random() for i in xrange(100)]A.append(l)B.append(m)

I would like the boxplots for A and B to appear next to each other, not on each other. Also, I would like more gap between the different x-values and perhaps thinner boxes. My code is below and so is the plot it produces (the present code puts A on top of B). Thanks for helping.

def draw_plot(data, edge_color, fill_color):bp = ax.boxplot(data, patch_artist=True)for element in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:plt.setp(bp[element], color=edge_color)plt.xticks(xrange(11))for patch in bp['boxes']:patch.set(facecolor=fill_color)fig, ax = plt.subplots()
draw_plot(A, "tomato", "white")
draw_plot(B, "skyblue", "white")
plt.savefig('sample_box.png', bbox_inches='tight')
plt.close()

enter image description here

Answer

Looking at the documentation of boxplot we find that it has a positions argument, which can be used to set the positions of the boxplots. You would need to supply a list or array with as many elements as you want to draw boxplots.

import numpy as np; np.random.seed(1)
import matplotlib.pyplot as pltA = np.random.rand(100,10)
B = np.random.rand(100,10)def draw_plot(data, offset,edge_color, fill_color):pos = np.arange(data.shape[1])+offsetbp = ax.boxplot(data, positions= pos, widths=0.3, patch_artist=True, manage_xticks=False)for element in ['boxes', 'whiskers', 'fliers', 'medians', 'caps']:plt.setp(bp[element], color=edge_color)for patch in bp['boxes']:patch.set(facecolor=fill_color)fig, ax = plt.subplots()
draw_plot(A, -0.2, "tomato", "white")
draw_plot(B, +0.2,"skyblue", "white")
plt.xticks(xrange(10))
plt.savefig(__file__+'.png', bbox_inches='tight')
plt.show()
plt.close()

enter image description here

https://en.xdnf.cn/q/70072.html

Related Q&A

perform() and reset_actions() in ActionChains not working selenium python

This is the code that habe no error: perform() and reset_actions() but these two functions have to work combinedly import os import time from selenium import webdriver from selenium.webdriver.common.ac…

nosetests not recognized on Windows after being installed and added to PATH

Im on exercise 46 of Learn Python the Hard Way, and Im meant to install nose and run nosetests. Ive installed nose already using pip, but when I run nosetests in the directory above the tests folder, I…

Using a context manager with mysql connector python

Im moving my code across from an sqlite database to mysql and Im having a problem with the context manager, getting the following attribute error.Ive tried combinations of mydb.cursor() as cursor, mydb…

Value of Py_None

It is clear to me that None is used to signify the lack of a value. But since everything must have an underlying value during implementation, Im looking to see what value has been used in order to sign…

Getting the href of a tag which is in li

How to get the href of the all the tag that is under the class "Subforum" in the given code?<li class="subforum"> <a href="Link1">Link1 Text</a> </l…

Put value at centre of bins for histogram

I have the following code to plot a histogram. The values in time_new are the hours when something occurred.time_new=[9, 23, 19, 9, 1, 2, 19, 5, 4, 20, 23, 10, 20, 5, 21, 17, 4, 13, 8, 13, 6, 19, 9, 1…

plot in Pandas immediately closes

I have a problem of plotting the data. I run the following python code:import pandas as pd df = pd.read_csv("table.csv")values = df["blah"] values.plot() print 1df[blahblah].plot() …

Django template: Embed css from file

Im working on an email template, therefor I would like to embed a css file<head><style>{{ embed css/TEST.css content here }}</style> </head>instead of linking it<head><…

handling async streaming request in grpc python

I am trying to understand how to handle a grpc api with bidirectional streaming (using the Python API).Say I have the following simple server definition:syntax = "proto3"; package simple;serv…

Add new column to a HuggingFace dataset

In the dataset I have 5000000 rows, I would like to add a column called embeddings to my dataset. dataset = dataset.add_column(embeddings, embeddings) The variable embeddings is a numpy memmap array of…