Tips for adjusting the voxel sizes in Matplotlib?

Looking to adjust the voxel dimensions using Matplotlib. How can I achieve this?

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.gca(projection='3d')
# Create grid
test2 = np.zeros((6, 6, 6))
# Activate single Voxel
test2[1, 0, 4] = True

ax.voxels(test2, edgecolor="k")
ax.set_xlabel('0 - Dim')
ax.set_ylabel('1 - Dim')
ax.set_zlabel('2 - Dim')

plt.show()

Instead of the voxel at position (1,0,4), I want to scale it to (0.5,0,2).

Answer №1

To customize the coordinates for the voxels function, refer to the API reference.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.gca(projection='3d')
# Creating a grid
test2 = np.zeros((6, 6, 6))
# Activating a single Voxel
test2[1, 0, 4] = True

# Defining custom coordinates for the grid
x,y,z = np.indices((7,7,7))/2

# Passing the custom coordinates as additional arguments
ax.voxels(x, y, z, test2, edgecolor="k")
ax.set_xlabel('0 - Dim')
ax.set_ylabel('1 - Dim')
ax.set_zlabel('2 - Dim')

plt.show()

The above code snippet would generate this output:

https://i.stack.imgur.com/JE7TU.png

Answer №2

voxels are capable of accepting the grid coordinates to position the voxels.

voxels([x, y, z, ]/, filled, ...)

x, y, z : a 3D np.array that is optional
These values represent the corners of the voxels. They should broadcast to a shape larger by one dimension in each direction compared to the shape of the filled input. This allows for plotting non-cubic voxels.

If these values are not specified, they default to increasing integers along each axis, similar to what is returned by indices(). Additionally, based on the / in the function signature, these arguments can only be passed positionally.

In this particular scenario,

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.gca(projection='3d')
# Create grid
voxels = np.zeros((6, 6, 6))
# Activate a single Voxel
voxels[1, 0, 4] = True

x,y,z = np.indices(np.array(voxels.shape)+1)

ax.voxels(x*0.5, y, z, voxels, edgecolor="k")
ax.set_xlabel('0 - Dimension')
ax.set_ylabel('1 - Dimension')
ax.set_zlabel('2 - Dimension')

plt.show()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Python, the shutil.move function is designed to move directories along with their

So I was coding in Python and encountered a problem that I can't seem to resolve. Here's the code snippet: import shutil import pathlib import os source_folder =(r'C:\Users\Acer\Desktop\New') destination_folder =(r ...

Having trouble retrieving the "Information" within the XML information model: <Personal Information> Information </Personal>

I'm trying to retrieve the "Data" from this XML data structure: <Name Attributes> Data </Name> Using Python's normal parsing with .attrib, I can only access the "Attributes" but I really need the "Data." Can you help explain what t ...

How is it possible that I can perform addition using a subtraction magic method?

This inquiry stems from my lack of understanding regarding the inner workings of Python rather than a pressing issue. I recently delved into magic methods and decided to experiment with them to grasp their functionality better. Surprisingly, amidst deliber ...

Pong Pygame Not Refreshing Scores

I'm having an issue with my score not updating correctly. Whenever a player scores, the debugger shows 0's. Here are the variables for tracking the scores. player_score = 0 opponent_score = 0 basic_font = pygame.font.Font('freesansbold.ttf& ...

The inclusive argument in pd.date_range() is not functioning as anticipated

There was a new feature introduced in pandas 1.40, which is the inclusive argument in the pd.date_range() class. After reading the documentation: inclusive{“both”, “neither”, “left”, “right”}, default “both” Include boundaries; Whethe ...

Selenium bypasses clicking on JavaScript pop-ups

Having trouble accessing the site externally, despite uploading the html file. Download HTML file here Please review the image below, I am trying to click on the red circular section. However, a JavaScript popup is preventing me from doing so. https:/ ...

Effortless content extraction between HTML tags using BeautifulSoup in Python

My Weather Data Extraction Project: I'm currently developing a webpage scraper to collect weather information. This is the progress I have made so far: import urllib.request from bs4 import BeautifulSoup # opening the webpage and storing the conten ...

Press the item by utilizing Selenium and Python

My attempt to click on the "Training material statistics" element using Python code was unsuccessful: WebDriverWait(driver,20)\ .until(EC.element_to_be_clickable((By.XPATH,'//*[@id="report-navigation"]/div[2]')))\ .cli ...

preserving information to prevent it from resetting every time I relaunch the program

I am interested in developing a debt collector program that allows me to save data for continuity. For instance, if an account balance is $100 and I make a payment of $20, the new balance should be $80. I want this updated balance to remain saved even afte ...

Tips for avoiding the need to provide the full directory path when using the subprocess library in Python

My issue involves a simple line of code that opens up a .exe file within the subprocess.call bracket. Each time I run the code, I have to provide the full path to the .exe file. Is there a way for me to avoid this by simply placing the .py file containing ...

kombu.exceptions.SerializeError: Unable to serialize user data in JSON format

I am currently working with a Django 1.11.5 application and Celery 4.1.0, but I keep encountering the following error: kombu.exceptions.EncodeError: <User: testuser> is not JSON serializable Here are my settings in settings.py: CELERY_BROKER_URL = ...

What is the best way to convert a Json File into a list of Rows?

I am attempting to import a JSON file into lists of Rows where each element in the list is a single row from the file. Check out the code snippet below with open("C:\Users\Derrick.Speirs\Desktop\jcpenney_reviewers.json", &qu ...

Setting up Python modules with IronPython

After creating a few functions in PyCharm using the Urllib.requests and Numpy packages, I encountered an issue. When attempting to use these functions in code written in IronPython for a GUI application, I received an exception stating that the modules did ...

What is the best method for extracting all links from a webpage using selenium?

Currently, I am attempting to scrape a website using Python, Selenium, and Beautifulsoup. However, when trying to extract all the links from the site, I keep encountering an issue with invalid string returns. Below is my current code snippet - could some ...

Encountering a TimeoutException while trying to scrape a blank Webelement with Python Selenium

I am currently working on a web scraping project to extract the names of Pet shops along with their addresses by iterating through different country states and cities. My goal is to export this data into an Excel file. However, I encountered a TimeoutExcep ...

Encountering difficulty transforming DataFrame into an HTML table

I am facing difficulties incorporating both the Name and Dataframe variables into my HTML code. Here's the code snippet I have: Name = "Tom" Body = Email_Body_Data_Frame html = """\ <html> <head> </he ...

The peculiar phenomenon observed in Python3

calculate: print(int( 342342342342342342 / 10 )) The result of the calculation is 34234234234234236 I'm perplexed by the appearance of the 6 at the end of the number! I attempted using "long" which resulted in an error. ...

What is the best way to ensure that your regular expression returns all capture groups?

Looking to extract specific values from a string that follows the pattern RAM 1000/2000/3000/4000. Using regular expressions, how can I extract RAM 1000, 2000, 3000, and 4000? I've tried using (RAM 1000)(?:(?:\/)(\w+)){1,}, but it only capt ...

Tips for effectively assigning rows to specific test cases

I'm currently facing a challenge where I have a series of TestCase instances and need to assign one username and password from the mainreader.py file for each TC. The issue is that I'm not sure how to achieve this. Each time a TC calls the mainre ...

Unable to transfer a bulky Excel document with Openpyxl

In a dilemma with a 9000 row x 30 column Excel file that needs to be transferred from one Excel workbook to another. The challenge arises when the code never seems to stop running, consuming a significant portion of my laptop's memory (screenshot). I ...