Creating tables using plotly - python-2.7

I am using plotly offline to create a table.But the output is displayed as a single row,not as shown in the output format given in the following link(i.e not as a table)
https://plot.ly/python/table/#changing-row-and-column-size(“Changing Row and column size”)
Here is the code,
import plotly
import plotly.graph_objs as go
#plotly.offline.init_notebook_mode()
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
values = [[['geneNames', 'uniprotIDs', 'ec-code', 'subcellularLocation', 'tissueSpecificity',
'proteinName', 'subunit', 'species']], [[' G6PC', ' P35575', ' 3.1.3.9',
' Endoplasmic reticulum membrane', 'No Data', ' Glucose-6-phosphatase alpha',
'No Data', ' Homo sapiens']]]
trace0 = go.Table(
type = 'table',
columnorder = [1,2],
columnwidth = [80,400],
header = dict(
values = [['<b>PARAMETERS</b>'],
['<b>VALUES</b>']],
line = dict(color = '#506784'),
fill = dict(color = '#119DFF'),
align = ['left','center'],
font = dict(color = 'white', size = 12),
height = 40
),
cells = dict(
values = values,
line = dict(color = '#506784'),
fill = dict(color = ['#25FEFD', 'white']),
align = ['left', 'center'],
font = dict(color = '#506784', size = 12),
height = 30
))
data = [trace0]
plot(data)
I would like to ask for some help
EDIT:
Would it be possible to save the table in png/txt format?I tried replacing 'uniprot.html' with 'uniprot.png'. But the file gets saved as uniprot.png.html.

Looks like as if the document and the current version of Plotly are out of sync. Try using a simple of list of two lists (column 1 and column 2).
values = [['geneNames', 'uniprotIDs', 'ec-code', 'subcellularLocation', 'tissueSpecificity', 'proteinName', 'subunit', 'species'],
[' G6PC', ' P35575', ' 3.1.3.9', ' Endoplasmic reticulum membrane', 'No Data', ' Glucose-6-phosphatase alpha', 'No Data', ' Homo sapiens']
]

Regarding your question about saving (figures) as PNG, check out orca. This is the graphing engine which sits behind plotly.
To be honest, it's a little fiddly at first, but easy once you get going, and it provides PNG support!

Related

Creating excell file with Django workbook and worksheet

I am trying to create excell report with django workbook and workseet as below.
def print_assistant_notes(request):
if request.method == 'GET':
notes = AssistantNotes.objects.filter(notedate=datetime.today().date()).order_by("time")
workbook = load_workbook(os.path.join(settings.BASE_DIR, "export_templates", "assistant_notes.xlsx"))
worksheet = workbook.active
title_cell = worksheet["A%d" % (1,)]
title_cell.value = "Assistant Notes [ "+str(datetime.today().date())+" ] "
row = 3
for note in notes:
time_cell = worksheet["A%d" % (row,)]
category_cell = worksheet["B%d" % (row,)]
note_cell = worksheet["C%d" % (row,)]
time_cell.value = note.time
category_cell.value = note.categories
note_cell.value = note.dailynote
row = row + 1
tmp_file = tempfile.NamedTemporaryFile()
workbook.save(tmp_file.name)
response = HttpResponse(smart_str(tmp_file.read()), content_type='application/vnd.ms-excel')
response["Content-Disposition"] = 'attachment; filename="assistant_notes.xlsx"'
return response
When i print report i get excell report as below in red color data. But i want it to be formatted as blue colored format. Because notes colum does not fit in print area as i mentioned it with blue arrow.
So i can say that my codes are generating report as the red part.
But i want it to fit in the printable area in blue part. So i want to be able to set cell sizes. And text will fit in that cell size left to right. Up to down cell size will be dynamic as text size may change.
If you're using openpyxl, you can actually change the styles of your cells, as outlined in the documentation:
from openpyxl.styles import Alignment
note_cell.alignment = Alignment(wrap_text=True)
Or create an alignment object before your for... loop and reuse it:
al = Alignment(wrap_text=True)
for note in notes:
...
note_cell = worksheet["C%d" % (row,)]
note_cell.alignment = al
which will be more memory-efficient.

Python 2.7 xlsxwriter isn't formatting data properly with valign

I have horizontal and vertical alignment set to center, but only the first two columns are centering the data.
The third column appears to be setting the data with a 'top' vertical alignment:
#!/usr/bin/env python
import xlsxwriter
# Create our spreadsheet.
workbook = xlsxwriter.Workbook('stats.xlsx')
worksheet = []
# Open our data file to extract data.
data = open('server_results','r')
# Create a bold centered font for our column headers.
format = workbook.add_format()
format.set_bold()
format.set_align('center')
format.set_align('vcenter')
format.set_text_wrap()
# Non-headers will be centered.
format1 = workbook.add_format()
format1.set_align('center')
format1.set_align('vcenter')
format1.set_text_wrap()
# Provider label/name for worksheet.
worksheet.append(workbook.add_worksheet('Stats'))
# Adjust column widths for data.
worksheet[0].set_column(0,2,25)
#worksheet[0].set_column(1,1,25)
#worksheet[0].set_column(1,2,25)
#worksheet[0].set_row(0,40)
# Start from the first cell. Rows and columns are zero indexed.
worksheet[0].write('A1', 'Column 1', format)
worksheet[0].write('B1', 'Column 2', format)
worksheet[0].write('C1', 'Column 3', format)
row = 1
col = 0
# Count lines
linelist = data.readlines()
count = len(linelist)
# Populate spreadsheet.
for num in range (0, count):
line = linelist[num]
splitline = line.split("\t")
worksheet[0].write(row, col, splitline[0], format1)
worksheet[0].write(row, col + 1, splitline[1], format1)
worksheet[0].write(row, col + 2, splitline[2], format1)
row += 1
#close workbook
workbook.close()
EOF
I've tried modifying how I format the data with following code:
format = workbook.add_format({'bold': True, 'bg_color': 'yellow', 'border': 5, 'align': 'center', 'valign': 'middle', 'text_wrap': True})
but when I do this, then NONE of the columns are centered -- with this format the first two columns are bottom aligned and third column is top aligned
The third column appears to be setting the data with a 'top' vertical alignment
I ran a version of your program with some sample data and I don't see that behaviour:
import xlsxwriter
# Create our spreadsheet.
workbook = xlsxwriter.Workbook('stats.xlsx')
worksheet = []
# Create a bold centered font for our column headers.
format = workbook.add_format()
format.set_bold()
format.set_align('center')
format.set_align('vcenter')
format.set_text_wrap()
# Non-headers will be centered.
format1 = workbook.add_format()
format1.set_align('center')
format1.set_align('vcenter')
format1.set_text_wrap()
# Provider label/name for worksheet.
worksheet.append(workbook.add_worksheet('Stats'))
# Adjust column widths for data.
worksheet[0].set_column(0,2,25)
# Start from the first cell. Rows and columns are zero indexed.
worksheet[0].write('A1', 'Column 1', format)
worksheet[0].write('B1', 'Column 2', format)
worksheet[0].write('C1', 'Column 3', format)
row = 1
col = 0
# Count lines
linelist = ['foo\tbar\tbaz\tbing'] * 5
count = len(linelist)
# Populate spreadsheet.
for num in range (0, count):
line = linelist[num]
splitline = line.split("\t")
worksheet[0].write(row, col, splitline[0], format1)
worksheet[0].write(row, col + 1, splitline[1], format1)
worksheet[0].write(row, col + 2, splitline[2], format1)
row += 1
#close workbook
workbook.close()
The output shows horizontal and vertical centering as expected:
Could you clarify what the issue is.
Using the following:
splitline = [l.rstrip() for l in line.split("\t")]
resolved the issue.

Input query for python code

So I have created this code for my research, but I want to use it for plenty of data files, I do not want to do it manually, which means retyping some lines in my code to use desired file. How to use input command in python (I work with python 2.7 on Windows OS) to use it faster, just by typing name of desired datafile. My code so far:
import iodata as io
import matplotlib.pyplot as plt
import numpy as np
import time
from scipy.signal import welch
from scipy import signal
testInstance = io.InputConverter()
start = time.time()
conversionError = io.ConversionError()
#data = testInstance.convert(r"S:\Doktorat\Python\", 1", conversionError)
data = testInstance.convert(r"/Users/PycharmProjects/Hugo/20160401", "201604010000", conversionError)
end = time.time()
print("time elapsed " + str(end - start))
if(conversionError.conversionSucces):
print("Conversion succesful")
if(conversionError.conversionSucces == False):
print("Conversion failed: " + conversionError.conversionErrorLog)
print "Done!"
# Create a new subplot for two cannals 1 & 3
a = np.amin(data.data)
Bx = data.data[0,]
By = data.data[1,]
dt = float(300)/266350
Fs = 1/dt
t = np.arange(0,300,dt*1e3)
N = len(Bx)
M = len(By)
time = np.linspace(0,300,N)
time2 = np.linspace(0,300,M)
filename = 'C:/Users/PycharmProjects/Hugo/20160401/201604010000.dat'
d = open(filename,'rb')
degree = u"\u00b0"
headersize = 64
header = d.read(headersize)
ax1 = plt.subplot(211)
ax1.set_title(header[:16] + ', ' + # station name
'Canals: '+header[32:33]+' and '+header[34:35]+ ', ' # canals
+'Temp'+header[38:43]+degree+'C' # temperature
+', '+'Time:'+header[26:32]+', '+'Date'+' '+header[16:26]) # date
plt.ylabel('Pico Tesle [pT]')
plt.xlabel('Time [ms]')
plt.grid()
plt.plot(time[51:-14], Bx[51:-14], label='Canal 1', color='r', linewidth=0.1, linestyle="-")
plt.plot(time2[1:-14], By[1:-14], label='Canal 3', color='b', linewidth=0.1, linestyle="-")
plt.legend(loc='upper right', frameon=False, )
# Create a new subplot for FFT
plt.subplot(212)
plt.title('Fast Fourier Transform')
plt.ylabel('Power [a.u.]')
plt.xlabel('Frequency Hz')
xaxis2 = np.arange(0,470,10)
plt.xticks(xaxis2)
fft1 = (Bx[51:-14])
fft2 = (By[1:-14])
plt.grid()
# Loop for FFT data
for dataset in [fft1]:
dataset = np.asarray(dataset)
freqs, psd = welch(dataset, fs=266336/300, window='hamming', nperseg=8192)
plt.semilogy(freqs, psd/dataset.size**0, color='r')
for dataset2 in [fft2]:
dataset2 = np.asarray(dataset2)
freqs2, psd2 = welch(dataset2, fs=266336/300, window='hamming', nperseg=8192)
plt.semilogy(freqs2, psd2/dataset2.size**0, color='b')
plt.show()
As you can see there are some places where it would be better to put input and when I run the code I can write names of filenames etc. to python instead of creating every single pythonfile, with specified info in the code.
Btw. I use Pycharm to my python.
If all you are trying to do is get rid of the hardcoded pathname, you should be able to format your name string with input variables
name = raw_input("Name: ")
measurement = raw_input("Measurement: ")
filename = "C:/Users/PycharmProjects/{0}/{1}".format(name, measurement)
see raw_input and string formatting

Python - reading text file delimited by semicolon, ploting chart using openpyxl

I have copied the text file to excel sheet separating cells by ; delimiter.
I need to plot a chart using the same file which I achieved. Since all the values copied are type=str my chart gives me wrong points.
Please suggest to overcome this. Plot is should be made of int values
from datetime import date
from openpyxl import Workbook,load_workbook
from openpyxl.chart import (
LineChart,
Reference,
Series,
)
from openpyxl.chart.axis import DateAxis
excelfile = "C:\Users\lenovo\Desktop\how\openpychart.xlsx"
wb = Workbook()
ws = wb.active
f = open("C:\Users\lenovo\Desktop\sample.txt")
data = []
num = f.readlines()
for line in num:
line = line.split(";")
ws.append(line)
f.close()
wb.save(excelfile)
wb.close()
wb = load_workbook(excelfile, data_only=True)
ws = wb.active
c1 = LineChart()
c1.title = "Line Chart"
##c1.style = 13
c1.y_axis.title = 'Size'
c1.x_axis.title = 'Test Number'
data = Reference(ws, min_col=6, min_row=2, max_col=6, max_row=31)
series = Series(data, title='4th average')
c1.append(series)
data = Reference(ws, min_col=7, min_row=2, max_col=7, max_row=31)
series = Series(data, title='Defined Capacity')
c1.append(series)
##c1.add_data(data, titles_from_data=True)
# Style the lines
s1 = c1.series[0]
s1.marker.symbol = "triangle"
s1.marker.graphicalProperties.solidFill = "FF0000" # Marker filling
s1.marker.graphicalProperties.line.solidFill = "FF0000" # Marker outline
s1.graphicalProperties.line.noFill = True
s2 = c1.series[1]
s2.graphicalProperties.line.solidFill = "00AAAA"
s2.graphicalProperties.line.dashStyle = "sysDot"
s2.graphicalProperties.line.width = 100050 # width in EMUs
##s2 = c1.series[2]
##s2.smooth = True # Make the line smooth
ws.add_chart(c1, "A10")
##
##from copy import deepcopy
##stacked = deepcopy(c1)
##stacked.grouping = "stacked"
##stacked.title = "Stacked Line Chart"
##ws.add_chart(stacked, "A27")
##
##percent_stacked = deepcopy(c1)
##percent_stacked.grouping = "percentStacked"
##percent_stacked.title = "Percent Stacked Line Chart"
##ws.add_chart(percent_stacked, "A44")
##
### Chart with date axis
##c2 = LineChart()
##c2.title = "Date Axis"
##c2.style = 12
##c2.y_axis.title = "Size"
##c2.y_axis.crossAx = 500
##c2.x_axis = DateAxis(crossAx=100)
##c2.x_axis.number_format = 'd-mmm'
##c2.x_axis.majorTimeUnit = "days"
##c2.x_axis.title = "Date"
##
##c2.add_data(data, titles_from_data=True)
##dates = Reference(ws, min_col=1, min_row=2, max_row=7)
##c2.set_categories(dates)
##
##ws.add_chart(c2, "A61")
### setup and append the first series
##values = Reference(ws, (1, 1), (9, 1))
##series = Series(values, title="First series of values")
##chart.append(series)
##
### setup and append the second series
##values = Reference(ws, (1, 2), (9, 2))
##series = Series(values, title="Second series of values")
##chart.append(series)
##
##ws.add_chart(chart)
wb.save(excelfile)
wb.close()
I have modified below code in for loop and it worked.
f = open("C:\Users\lenovo\Desktop\sample.txt")
data = []
num = f.readlines()
for line in num:
line = line.split(";")
new_line=[]
for x in line:
if x.isdigit():
x=int(x)
new_line.append(x)
else:
new_line.append(x)
ws.append(new_line)
f.close()
wb.save(excelfile)
wb.close()
For each list,for each value check if its a digit, if yes converts to integer and store in another list.
Using x=map(int,x) didnt work since I have character values too.
I felt above is much more easy than using x=map(int,x) with try and Except
Thanks
Basha

How to read specific column data from xlsx and update to js file in python?

// Morris.js Charts sample data for SB Admin template
$(function() {
$('input[name="daterange"]').daterangepicker();
// Area Chart Resumes
Morris.Area({
element: 'morris-area-chart-2',
data: [{
period: '2016-08',
company0: 524252,
company1: 0,
company2: 68076,
company3: 11745,
company4: 0,
company5: 4896,
}],
});
// Area Chart JDs
Morris.Area({
element: 'morris-area-chart',
data: [{
{
period: '2016-08',
company0: 524252,
company1: 0,
company2: 68076,
company3: 11745,
company4: 0,
company5: 4896,
}],
});
Problem:
1) First i want to read data from 'Total resumes' column.
2) After reading data,Update those data in .js file according to the name.
If row is empty then update it with 0 value.
This is how .js file structure looks like.
Please refer screen shots for reference
I don't think it is perfect, but it is working
change your .xlsx file to csv and run below code
def generate(company, val):
if(val == ''):
val = '0'
return '\t' + company + ' : ' + val + '\n'
f = open('resume.csv', 'r')
data = f.read().split('\n')
result = ''
for i in range(1, len(data)-1):
row = data[i].split(',')
result = result + generate(row[1], row[4])
print result
js_file = open('data1.js').read()
start = js_file.find('data: [{')
while(start!=-1):
end = js_file.find('}],', start+1)
output = js_file[0:start] + 'data : [{\n' + result + js_file[end:] + '\n\t}],'
print output
output_file = open('data1.js', 'w').write(output)
js_file = open('data1.js').read()
start = js_file.find('data: [{')
only one time it will work, if you want to run next time also
change start = js_file.find('data: [{') to start = js_file.find('data : [{')
output = js_file[0:start] + 'data : [{\n' + result + js_file[end:] + '\n\t}],'
to
output = js_file[0:start] + 'data: [{\n' + result + js_file[end:] + '\n\t}],'
observe just i am changing spaces in data: [ to data : [
and if you want again and again change alternatively. Go through the code you will understood i think
my .csv file check it is matching with your's or not
s.no,company,total job,cumulative,total resumes,resume cumulate
1,company0,40079,4645,330,4543
2,company1,,,,345
3,company2,23250,5345,68076,3245
4,company3,728,435,11745,3245
5,company4,10,345,4896,345