Как я могу произвести графики студенческого стиля с помощью matplotlib?

Я экспериментирую с matplotlib в данный момент. Некоторое время назад я использовал код Excel VBA произвести изображения, такие как присоединенное то.

Вы заметите, что это не представлено в научном стиле / стиле исследования, а скорее как будто произведенный учеником школы на миллиметровке - с тремя другими линиями сетки разрабатывает.

Существует ли довольно простой способ достигнуть этого вида вещи с matplotlib?

alt text

6
задан Community 8 February 2017 в 14:22
поделиться

2 ответа

Да, для этого можно использовать шипы .

import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import numpy as np

fig = plt.figure(1)
ax = fig.add_subplot(111)

# set up axis
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

# draw curve
x = np.arange(-2.5,2.5,0.01)
line, = ax.plot(x, x**2)

#set bounds
ax.set_ybound(-1,7)

# create grid
#ax.xaxis.set_major_locator(MultipleLocator(1))
#ax.xaxis.set_minor_locator(MultipleLocator(0.2))
#ax.yaxis.set_major_locator(MultipleLocator(1))
#ax.yaxis.set_minor_locator(MultipleLocator(0.2))
#ax.xaxis.grid(True,'minor')
#ax.yaxis.grid(True,'minor')
#ax.xaxis.grid(True,'major',linewidth=2)
#ax.yaxis.grid(True,'major',linewidth=2)

#adjust grid on the 2s
#for idx,loc in enumerate(ax.xaxis.get_majorticklocs()):
    #if loc !=0 and loc % 2 == 0: ax.get_xgridlines()[idx].set_c('r')
#for idx,loc in enumerate(ax.yaxis.get_majorticklocs()):
    #if loc !=0 and loc % 2 == 0: ax.get_ygridlines()[idx].set_c('r')

## THIS IS THE EDIT
ax.xaxis.set_minor_locator(MultipleLocator(0.2))
ax.yaxis.set_minor_locator(MultipleLocator(0.2))
ax.xaxis.grid(True,'minor',linewidth=2)
ax.yaxis.grid(True,'minor',linewidth=2)

minor_grid_lines = [tick.gridline for tick in ax.xaxis.get_minor_ticks()]
for idx,loc in enumerate(ax.xaxis.get_minorticklocs()):
    if loc % 2.0 == 0: minor_grid_lines[idx].set_c('r' )
    elif loc % 1.0 == 0: minor_grid_lines[idx].set_c('g' )
    else: minor_grid_lines[idx].set_c( 'b' )

plt.show()

alt text

8
ответ дан 10 December 2019 в 00:37
поделиться

Еще одна мысль - я также пытался сделать все это с помощью второстепенных линий сетки (помимо всего прочего, это поможет моему пониманию), но это не так. перечисление правильно, без сомнения, из-за get_minorticklocs и ax.get_xgridlines. Извините и заранее спасибо ...

Geddes

import matplotlib.pyplot as plt 
from matplotlib.ticker import MultipleLocator, FormatStrFormatter 
import numpy as np 

fig = plt.figure(1) 
ax = fig.add_subplot(111) 

# set up axis 
ax.spines['left'].set_position('zero') 
ax.spines['right'].set_color('none') 
ax.spines['bottom'].set_position('zero') 
ax.spines['top'].set_color('none') 
ax.xaxis.set_ticks_position('bottom') 
ax.yaxis.set_ticks_position('left') 

# draw curve 
x = np.arange(-2.5,2.5,0.01) 
line, = ax.plot(x, x**2) 

#set bounds 
ax.set_ybound(-1,7) 

# create grid 
ax.xaxis.set_minor_locator(MultipleLocator(0.2)) 
ax.yaxis.set_minor_locator(MultipleLocator(0.2)) 
ax.xaxis.grid(True,'minor',linewidth=2) 
ax.yaxis.grid(True,'minor',linewidth=2) 

#adjust grid on the 2s 
for idx,loc in enumerate(ax.xaxis.get_minorticklocs()):
    if loc % 2 == 0: ax.get_xgridlines()[idx].set_color('r')
    if loc % 1 == 0: ax.get_xgridlines()[idx].set_color('g')
    if loc % 0.2 == 0: ax.get_xgridlines()[idx].set_color('b')

for idx,loc in enumerate(ax.yaxis.get_majorticklocs()): 
    if loc % 2 == 0: ax.get_ygridlines()[idx].set_c('b') 

plt.savefig('spines3.png',dpi=300)
1
ответ дан 10 December 2019 в 00:37
поделиться
Другие вопросы по тегам:

Похожие вопросы: