Investigue sobre el diagrama de Hertzprung-Russell, una herramienta muy potente en astronomia, y describa un poco al respecto para darle contexto al resto de la tarea El objetivo es generar un diagrama HR lo más parecido al de esta referencia.
No lucirá idéntico por que no se usarán exactamente los mismos datos, y las unidades pueden ser ligeramente distinta. La idea sí es dejar su figura lo más parecida a la de referencia en el estilo: colores, escalas en los ejes, tamaño de los marcadores, leyendas, textos en el gráfico, etc.
Los datos para crear la figura están en la carpeta Data. Cada tabla contiene las informaciones sobre un tipo de estrellas según indican los nombres de archivo. La información viene en 3 columnas: luminosidad en luminosidades solares, Temperatura en Kelvin y Radio de la estrella en unidades arbitrarias La idea es que cada estrella en el gráfico tenga un color representativo
de su temperatura (que estrellas frías son rojas y estrellas calientes son azules) y que el tamaño del símbolo sea representativo del tamaño de cada estrella para diferenciar entre enanas, gigantes y estrellas de secuencia principal
Busque que su código sea semi automático; es indispensable leer los datos desde el propio programa, no copiarlos a mano, y hallar una forma de obtener los tamaños y colores sin declararlos uno a uno
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
stars = []
i=0
data1 = np.loadtxt("data/giants.txt", delimiter=" ", skiprows=1)
for x in range(len(data1)):
stars.append("Giants")
data2 = np.loadtxt("data/supergiants.txt", delimiter=" ", skiprows=1)
for x in range(len(data2)):
stars.append("Supergiants")
data3 = np.loadtxt("data/dwarfs.csv", delimiter=",", skiprows=1)
for x in range(len(data3)):
stars.append("Dwarfs")
data4 = np.loadtxt("data/ms.csv", delimiter=",", skiprows=1)
for x in range(len(data4)):
stars.append("Main sequence")
data= np.concatenate((data1,data2,data3,data4), axis=0)
T= data[:, 1] #Temperature
L= data[:, 0] #Luminosity
area= data[:, 2] #ratio
radius=20*(area) #multiplying by 20 the value of ratio
log_temp=np.log10(T) #Taking in account logaritmic value of T for colour parameter of plotting
fig = plt.figure(figsize=(12,8))
plt.scatter(T, L,
#c=colors,
c=log_temp,
#hue=log_temp,
s=radius,
marker='o',
#cmap='hsv',
cmap='Spectral',
lw=1,
edgecolors='gray',
alpha=0.9)
plt.title=('diagrama de Hertzprung-Russell')
plt.xlabel("Temperature (K)", fontsize=20, fontweight='bold')
plt.ylabel("Luminosity ($L_{sun}$)", fontsize=20, fontweight='bold')
plt.yscale('log')
plt.xscale('log')
idx = [4000,6000,8000,12000]
plt.xticks(idx, fontsize=10, fontweight='bold')
plt.yticks(fontsize=10, fontweight='bold')
plt.xlim(14000, 3000)
plt.ylim(0.00001, 10000000)
#Adding the Axes object ax: It is a container that holds the axes, the ticks, the labels, the plot, the legend, etc.
ax = plt.axes()
#Method for generate lines only in X and Y axis
#removing top and right borders
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#Modifying ticks of X axis to eliminate scientific notation
from matplotlib.ticker import FuncFormatter
def Wscientific(x, pos):
return '%1i' % (x)
formatter = FuncFormatter(Wscientific)
ax.xaxis.set_major_formatter(formatter)
plt.setp(ax.get_xminorticklabels(), visible=False)
#Adding text to the plot describing the used data
ax.set_facecolor("white")
ax.text(7000,15000,'Giants', style='normal',color='black', fontsize=20, fontweight='bold')
ax.text(11000,0.5,'Main sequence', style='normal',color='black', fontsize=20, fontweight='bold')
ax.text(11000,0.0001,'Dwarfs', style='normal',color='black', fontsize=20, fontweight='bold')
plt.show()
Después de tener un diseño de base para el ejercicio No. 1, en este ejercicio se pide generar una animación, en la cual se reproduzca el mismo gráfico de antes pero las estrellas vayan apareciendo progresivamente
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
def salvar_figura(x,y,co,z,n):
fig = plt.figure(figsize=(12,8))
scat = plt.scatter(x, y,
c=co,
s=z,
marker='o',
cmap='Spectral',
lw=1,
edgecolors='gray',
alpha=0.9)
plt.xlabel("Temperature (K)", fontsize=20, fontweight='bold')
plt.ylabel("Luminosity ($L_{sun}$)", fontsize=20, fontweight='bold')
plt.yscale('log')
plt.xscale('log')
idx = [4000,6000,8000,12000]
plt.xticks(idx, fontsize=10, fontweight='bold')
plt.yticks(fontsize=10, fontweight='bold')
plt.xlim(14000, 3000)
plt.ylim(0.00001, 10000000)
#Adding the Axes object ax: It is a container that holds the axes, the ticks, the labels, the plot, the legend, etc.
ax = plt.axes()
#Method for generate lines only in X and Y axis
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
#Modifying ticks of X axis to eliminate scientific notation
from matplotlib.ticker import FuncFormatter
def Wscientific(x, pos):
return '%1i' % (x)
formatter = FuncFormatter(Wscientific)
ax.xaxis.set_major_formatter(formatter)
plt.setp(ax.get_xminorticklabels(), visible=False)
plt.savefig("Animation"+str(n)+".png", format="png")
VectX=[]
VectY=[]
VectC=[]
VectZ=[]
n=0
for i in range(len(T)):
VectX.append(T[n])
VectY.append(L[n])
VectC.append(log_temp[n])
VectZ.append(radius[n])
salvar_figura(VectX,VectY,VectC,VectZ,n)
n=n+1
plt.show()
from PIL import Image
import glob
# Create the frames
frames = []
imgs = glob.glob("*.png")
for i in imgs:
new_frame = Image.open(i)
frames.append(new_frame)
#Save into a GIF file that loops forever
frames[0].save('Hertzprung-Russell.gif', format='GIF',
append_images=frames[1:],
save_all=True,
duration=300, loop=10)