Showing posts with label formatting. Show all posts
Showing posts with label formatting. Show all posts

Thursday, September 20, 2018

Is there a non-math version of matplotlib.ticker.LogFormatterSciNotation?

Leave a Comment

I am trying to plot a graph with a logarithmic y-axis using pgf_with_latex, i.e. all text formatting is done by pdflatex. In my matplotlib rc Parameters I define a font to be used. Here comes my problem: The standard matplotlib.ticker.LogFormatterSciNotation formatter used math text and therefore a math font, which does not fit the rest of the fonts (sans-serif).

How can I format the y-axis labels using a formatter from matplotlib.ticker so that I get the labels formatted as powers of 10 with superscripted powers? To be more specific: How do I get these yticklabels formatted the same way but with the font from the xticklabels?

I already tried using different formatters provided by matplotlib.ticker, but none of them has the exponents written the way I want.

Here is an example of what I mean with a MWE below. example plot

import matplotlib as mpl  mpl.use('pgf') pgf_with_latex = {         "pgf.texsystem": "pdflatex",         "font.family": "sans-serif",         "text.usetex": False,         "pgf.preamble": [             r"\usepackage[utf8x]{inputenc}",             r"\usepackage{tgheros}",  # TeX Gyre Heros sans serif             r"\usepackage[T1]{fontenc}"             ]         }  mpl.rcParams.update(pgf_with_latex) import matplotlib.pyplot as plt  fig = plt.figure(figsize=[3, 2]) ax = fig.add_subplot(111) ax.set_yscale("log") ax.minorticks_off() ax.set_xlabel("sans-serif font label") ax.set_ylabel("math font label") plt.gca().set_ylim([1, 10000]) plt.gcf().tight_layout()   plt.savefig('{}.pdf'.format("test")) 

Caution: A TeX distribution has to be installed on your system to run this. I used MikTex 2.9. Also Python 3.6.2 and matplotlib 2.1.2.

2 Answers

Answers 1

You could subclass LogFormatterExponent to format the ticks with "10\textsuperscript{x}" where x is the exponent. This would not use math mode tex, i.e. no $ signs around the text, and therefore would use the textfont specified in the preamble (in this case the font without serifs).

import matplotlib as mpl from matplotlib.ticker import LogFormatterExponent  mpl.use('pgf') pgf_with_latex = {         "pgf.texsystem": "pdflatex",         "font.family": "sans-serif",         "text.usetex": False,         "pgf.preamble": [             r"\usepackage[utf8x]{inputenc}",             r"\usepackage{tgheros}",  # TeX Gyre Heros sans serif             r"\usepackage[T1]{fontenc}"             ]         } mpl.rcParams.update(pgf_with_latex) import matplotlib.pyplot as plt  class LogFormatterTexTextMode(LogFormatterExponent):     def __call__(self, x, pos=None):         x = LogFormatterExponent.__call__(self, x,pos)         s = r"10\textsuperscript{{{}}}".format(x)         return s  fig = plt.figure(figsize=[3, 2]) ax = fig.add_subplot(111) ax.set_yscale("log") ax.yaxis.set_major_formatter(LogFormatterTexTextMode()) ax.minorticks_off() ax.set_xlabel("sans-serif font label") ax.set_ylabel("text mode tex label") plt.gca().set_ylim([0.01, 20000]) plt.gcf().tight_layout()   plt.savefig('{}.pdf'.format("test")) 

enter image description here

Answers 2

You can define your own FuncFormatter that does the scientific notation in unicode.

An almost complete converter to superscript was given in this answer. I just added the minus.

Here's an implementation:

# -*- coding: utf-8 -*- from math import log10  SUPERSCRIPTS = dict(zip(u"-0123456789", u"⁻⁰¹²³⁴⁵⁶⁷⁸⁹")) def unicode_sci_notation(x, pos):     """Scientific notation of number with unicode"""     power = int(log10(x))     mantissa = x/(10**power)     superscript = u''.join(SUPERSCRIPTS[c] for c in unicode(power))     if mantissa == 1:         return '10%s' % superscript     else:         return '%.2f x 10%s' % (mantissa, superscript) formatter = mpl.ticker.FuncFormatter(unicode_sci_notation)  ax.yaxis.set_major_formatter(formatter) 

To do it this way, you need to specify coding: utf-8 at the top of your script. If you don't want that, you can escape the unicode characters as explained in the answer I linked.

enter image description here

Read More

Tuesday, April 25, 2017

How to export html table to excel with correct latitude/longitude format?

Leave a Comment

I have an HTML table that contains 2 columns of latitudes and longitudes. I can easily export this table to excel using the following JavaScript function:

function downloadExcel() { var tab_text = '<html xmlns:x="urn:schemas-microsoft-com:office:excel"> <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">'; tab_text = tab_text + '<head><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';  tab_text = tab_text + '<x:Name>Results</x:Name>';  tab_text = tab_text + '<x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet>'; tab_text = tab_text + '</x:ExcelWorksheets></x:ExcelWorkbook></xml></head><body>';  tab_text = tab_text + "<table border='1px'>"; tab_text = tab_text + $('#gcResults_table').html(); tab_text = tab_text + '</table></body></html>';  var data_type = 'data:application/vnd.ms-excel; charset=UTF-8;base64,';  var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE ");  if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {     if (window.navigator.msSaveBlob) {         var blob = new Blob([tab_text], {             type: "application/csv;charset=utf-8;"         });         navigator.msSaveBlob(blob, 'Results.xls');     } } else {     $('#test').attr('href', data_type + ', ' + encodeURIComponent(tab_text));     $('#test').attr('download', 'Results.xls'); } }// END of downloadExcel() 

It works perfectly. But when an excel file has exported the table, latitudes and longitudes are not shown in correct format. A sample row of the excel file can be seen below:

enter image description here

Therefore, my question is, how can I correctly write these coordinates to excel? I have searched allot on several blogs but have not been able to find a solution. Thanks allot for your time and support.

UPDATE: Using the above excel export method, whenever an xls file is exported, I get the following notification when I open the file in MS Excel:

enter image description here

After clicking on "Yes", it shows me the excel data but format of latitude/longitude is not correct, as it is mentioned above.

3 Answers

Answers 1

You must specify the data type of the cells as string for xml spreadsheet format. Your table should look like:

<Table border='1px'>     <Column ss:Width="75" ss:AutoFitWidth="0"/>     <Row>       <Cell>           <Data ss:Type="String">48.210221, 16.390036</Data>       </Cell>     </Row> </Table> 

For the mhtml file format a simple table like in the following code, works fine for me:

<html xmlns:x="urn:schemas-microsoft-com:office:excel">  <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">   <head>     <xml>       <x:ExcelWorkbook>      <x:ExcelWorksheets>             <x:ExcelWorksheet>         <x:Name>Results</x:Name>         <x:WorksheetOptions>             <x:Panes></x:Panes>         </x:WorksheetOptions>         </x:ExcelWorksheet>      </x:ExcelWorksheets>        </x:ExcelWorkbook>     </xml>   </head>   <body>      <table border='1px'>         <tr>            <td >48.210221, 16.390036</td>         </tr>       </table>   </body> </html> 

Be sure that inside the file are indeed those values. Maybe the values are transformed before being saved to the file.

The warning that you get, it's because you are not saving real Excel (xls) file. You have an html file saved with xls extension. MS Excel knows to read HTML files and to display them into a worksheet.

Answers 2

There is a problem on this because excel (mso-number-format) doesn't support that type of number. I would go and format it as text if thats possible in your case.

See this link for avaliable mso-number-formats and this link for a reformatting in excel.

Try to add these css classes

.text {    mso-number-format: "\@"; } .number {    mso-number-format: General; } 

And give these css classes to your data fields.

<div class="text">11</div> <div class="number">11.0</div> 

Answers 3

Just export from JS as CSV-File and format the coordinates with the syntax ="[NUM]". Like this:

Name;Lat;Lng Test1;="32.056717";="11.335333" Test2;="12.056717";="19.335333" 

In Excel:

enter image description here

Read More

Saturday, April 23, 2016

Why json format can't has the same ID value of different object?

Leave a Comment

I'm having problem when I set the same id value of different object's attribute like below : "timestampId":4,"UserId":4,"ParentId":4,

enter image description here

but when i change to different value, It works properly :

enter image description here

2 Answers

Answers 1

JSON itself can have the same value in different attributes — there is nothing wrong with it.

It is your API endpoint (http://localhost:8080/eHealthBackend/NewUserAccountParent) that does not accept the same value for certain attributes. Apparently it has some validation logic doing that, for example a user's parentId cannot be the same as userId which kind of makes sense — you cannot be parent to yourself.

Answers 2

I think @DrakeES is right,there might be some validation in Your API,as per the data, when you check the working example image which you have put here,you can see that you are sending the PARENTID:6, but you are getting PARENTID:2 as response.

Read More

Friday, April 15, 2016

Multiline string alignment / indenting in Eclipse

Leave a Comment

I'm using Eclipse Luna and I want to align / indent multi-line string literals so that that each line begins on the same column. But I'm having trouble convincing Eclipse to do it in the Code Style Formatter.

This is how it's currently formatting:

    final String string1 =         "abc" +             "def" +             "ghi";      System.out.println(         "abc" +             "def" +             "ghi");      System.out.println("" + // an ugly workaround         "abc" +         "def" +         "ghi");      method("xyz",         "" +           // Especially ugly in this case             "abc" +             "def" +             "ghi"); 

But this is what I really want:

    final String string2 =         "abc" +         "def" +         "ghi";      System.out.println(         "abc" +         "def" +         "ghi");      // Or something like this would be fine too     final String string3 =         "abc"       + "def"       + "ghi";      System.out.println(         "abc"       + "def"       + "ghi"); 

It seems like such a simple and desirable format. Just start each part of the broken-up line on the same column. But I haven't been able to find a way to do it anywhere.

1 Answers

Answers 1

The following settings sort of work for your 2 first examples. Copy paste the your example into a block and then reformat. With this setting however you need to manually break the lines, the formatter will then indent them and keep from joining them. You will probably need to tweek other settings since the "default indention for wrapped lines" is 0.

Under Line Wrapping:

  1. Check "Never join already wrapped lines"

  2. Set "Default indention for wrapped lines:" to 0

  3. Expressions / Assignments:

    • Wrap where necessary,
    • Indent by one
  4. Expressions / Binary expressions:

    • Wrap where necessary,
    • Check Wrap before operator,
    • Default indention

There is also the option to disable the formatter and then re-enable it after the code you want to format manually. This can be useful when you have tabular data in initializers you want to format for readability. This is under Off/On Tags in the formatter settings.

Read More